casillas
casillas

Reputation: 16813

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);
    }
}

Upvotes: 0

Views: 98

Answers (2)

Alex
Alex

Reputation: 38529

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

Upvotes: 2

YuriG
YuriG

Reputation: 368

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()

Upvotes: -1

Related Questions