pages

Friday, 6 December 2013

Distinct Keyword in LINQ

Few days back when I was trying to Filter my result set using Linq Distinct keyword I got into a situation. The keyword didn't worked for me, I was getting same result set with or without Linq.

I Goggled for the solution, But most of the solutions offered to user the Group By operator. which is as follows:

Take an entity that contains following fields:
id, Name.
public class MyDemo
{

public int id{get; set;};

public string Name {get; set;};

}
MyDemo ListData = new MyDemo
{
id=1, Name="Alpha";
id=2, Name="Beta";
id=1, Name="Alpha";
id=3, Name="Gamma";
}
MyDemo ListResult;


ListResult = (ListData.Select(t => t).GroupBy(x => x.Name).Select(y => y.First()).ToList()

Distinct Keyword is little tricky in Linq. At first it would not work same like Distinct in sql server Linq to Object behaves little weird because all are distinct object references so the other way round to this problem is use a GroupBy Operator.

We can get the solution to this problem by introducing an anonymous type to store the result and in that case we will get the desired result.

var result =  (from d in ListData select new { d.id, d.Name }).Distinct();

No comments:

Post a Comment