Select distinct using linq

C#LinqListClass

C# Problem Overview


I have a class list of class

public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
}


List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest() { id = 1, value = "a" });
myList.Add(new LinqTest() { id = 1, value = "b" });
myList.Add(new LinqTest() { id = 2, value = "c" });

I need to select only the distinct id's from that list. ie, my resultant list should only contain

[{id=1,value="a"},{ id = 2, value = "c" }]

How can I do this with linq?

Edit

Input,

id      value
1        a
1        b
2        c
3        d
3        e

Out put should be,

id      value
1        a
2        c
3        d

ie, if there is a repetition of id, result should take the first occurrence only.

C# Solutions


Solution 1 - C#

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

Solution 2 - C#

Using morelinq you can use DistinctBy:

myList.DistinctBy(x => x.id);

Otherwise, you can use a group:

myList.GroupBy(x => x.id)
      .Select(g => g.First());

Solution 3 - C#

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

Solution 4 - C#

myList.GroupBy(i => i.id).Select(group => group.First())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnoop Joshi PView Question on Stackoverflow
Solution 1 - C#Paul RuaneView Answer on Stackoverflow
Solution 2 - C#Daniel HilgarthView Answer on Stackoverflow
Solution 3 - C#Tim SchmelterView Answer on Stackoverflow
Solution 4 - C#Tim RogersView Answer on Stackoverflow