简体   繁体   中英

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. 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?

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
46
55
17

in your LG object, you'll need to override the Equals and the GetHashCode methods.
Once you've done that, you can use the Distinct() function in LINQ

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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