C# Linq 查找唯一项
C# Linq find unique item
我正在寻找一种在列表中查找唯一项的方法:
List<Item> list = new List<Item>();
list.Add(new Item() { id = 1, name = "test" });
list.Add(new Item() { id = 2, name = "test" });
list.Add(new Item() { id = 3, name = "test1"});
list.Add(new Item() { id = 4, name = "test2"});
list.Add(new Item() { id = 5, name = "test2"});
var uniqueItems = ?
uniqueItems 应该包含 { id = 3, name = "test1"} 因为 test1 是唯一的
实现它的最佳方法是什么?
您可以像这样使用 linq 运算符 Where 和 Count
var uniqueItems = list.Where(x => list.Count(item => item.name == x.name) == 1);
几种方式(使用Linq
):
var uniqueItems = list.Where(item => list.Count(li => String.Equals(item.name, li.name)) == 1);
//or
var uniqueItems = list
.GroupBy(item => item.name)
.Where(g => g.Count() == 1)
.SelectMany(g => g);
list.GroupBy(x => x.Name)
.Where(x => x.Count() == 1)
.Select(x => new Item { id = x.First().id, name = x.Key });
我正在寻找一种在列表中查找唯一项的方法:
List<Item> list = new List<Item>();
list.Add(new Item() { id = 1, name = "test" });
list.Add(new Item() { id = 2, name = "test" });
list.Add(new Item() { id = 3, name = "test1"});
list.Add(new Item() { id = 4, name = "test2"});
list.Add(new Item() { id = 5, name = "test2"});
var uniqueItems = ?
uniqueItems 应该包含 { id = 3, name = "test1"} 因为 test1 是唯一的
实现它的最佳方法是什么?
您可以像这样使用 linq 运算符 Where 和 Count
var uniqueItems = list.Where(x => list.Count(item => item.name == x.name) == 1);
几种方式(使用Linq
):
var uniqueItems = list.Where(item => list.Count(li => String.Equals(item.name, li.name)) == 1);
//or
var uniqueItems = list
.GroupBy(item => item.name)
.Where(g => g.Count() == 1)
.SelectMany(g => g);
list.GroupBy(x => x.Name)
.Where(x => x.Count() == 1)
.Select(x => new Item { id = x.First().id, name = x.Key });