public class Student { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } Liststudents = new List (); students.Add(new Student { ID = 1, Name = "Adam", Age = 15 }); students.Add(new Student { ID = 2, Name = "Tom", Age = 15 }); students.Add(new Student { ID = 3, Name = "John", Age = 15 }); students.Add(new Student { ID = 4, Name = "Abraham", Age = 15 }); students.Add(new Student { ID = 5, Name = "Abraham", Age = 15 }); /*Find students having same name*/ var samename = students.GroupBy(x => x.Name).Where(g => g.Count() > 1).Select(y => new { Code = y.Key, Desc = y.First() }).ToDictionary(z => z.Code, z => z.Desc); /*Select distinct name of students*/ var distinctnames = students.GroupBy(x => x.Name).Where(g => g.Count() >0).Select(y => new { Code = y.Key, Desc = y.First() }).ToDictionary(z => z.Code, z => z.Desc);
Wednesday, March 28, 2012
LINQ - Get distinct values from collection
Below Code snippet shows how to select distinct values from generic collection using LINQ
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment