Distinct Objects in Linq
When we working with collection of objects & when we need to select the distinct objects out of it, linq Distinct() does not work as we expect.That supports to get the distinct of some know types like,string, Guid, int and etc. What if we need to get the distinct members of a collection where collection is made up of complex object type. You can use the following code snippet.
Suppose the Class is Defined as follows where each member object will have a unique name for it.
public class Member
{
public string UniqueName{get;set;}
public int MemberLevel{get;set;}
public string HeirachyName{get;set;}
}
List<Member> memberCollection=new List<Member>();
if we want to get the distinct members from the above collection.
List<Member> DistinctMember=memberCollection.GroupBy(x=>x.UniqueName).Select(x => x.ElementAt(0)).ToList();
This will select the distict member objects from the collection.
Suppose the Class is Defined as follows where each member object will have a unique name for it.
public class Member
{
public string UniqueName{get;set;}
public int MemberLevel{get;set;}
public string HeirachyName{get;set;}
}
List<Member> memberCollection=new List<Member>();
if we want to get the distinct members from the above collection.
List<Member> DistinctMember=memberCollection.GroupBy(x=>x.UniqueName).Select(x => x.ElementAt(0)).ToList();
This will select the distict member objects from the collection.
Comments
Post a Comment