简体   繁体   English

使用LINQ获取列表中的所有DISTINCT项

[英]Get all DISTINCT items in the List with LINQ

I am quite new to LINQ, I have the following script which returns me the first item in the table if condition meets, however, I would like to get all distinct items not only the first one. 我对LINQ很陌生,我有以下脚本,如果条件满足,该脚本将表中的第一项返回给我,但是,我希望获得所有不同的项,而不仅仅是第一个。 I am relatively new on this platform. 我在这个平台上还比较陌生。

public LG GetLG (int WID)
{
    lock (locker) {
      return database.Table<LG> ().FirstOrDefault (x => x.id == WID);
    }
}

Is .Distinct() what you're looking for? 您正在寻找.Distinct()吗?

return database.Table<LG>.Where(x => x.id == WID).Distinct()

The following link contains useful material: 以下链接包含有用的材料:

Example: 例:

List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

IEnumerable<int> distinctAges = ages.Distinct();

Console.WriteLine("Distinct ages:");

foreach (int age in distinctAges)
{
  Console.WriteLine(age);
}

This code produces the following output: 此代码产生以下输出:

Distinct ages: 不同年龄段:
21 21
46 46
55 55
17 17

in your LG object, you'll need to override the Equals and the GetHashCode methods. LG对象中,您需要覆盖EqualsGetHashCode方法。
Once you've done that, you can use the Distinct() function in LINQ 完成此操作后,可以在LINQ中使用Distinct()函数。

database.Table<LG>.Where(x => x.id == WID).Distinct()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM