linq unique in csharp

To get unique values from a list using LINQ, you can use the Distinct method which returns the distinct elements from a sequence by using the default equality comparer to compare values. Here is an example:

main.cs
List<int> numbers = new List<int> { 1, 2, 3, 3, 4, 4, 5 };
var uniqueNumbers = numbers.Distinct();

foreach (var number in uniqueNumbers)
{
    Console.WriteLine(number);
}
173 chars
8 lines

This will output:

main.cs
1
2
3
4
5
10 chars
6 lines

You can also get unique elements based on a specific property of objects in a list using grouping. Here is an example:

main.cs
List<Person> people = new List<Person> 
{
    new Person { Name = "John", Age = 20 },
    new Person { Name = "Mary", Age = 25 },
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Mary", Age = 35 }
};

var uniquePeople = people.GroupBy(p => p.Name)
                         .Select(g => g.First());

foreach (var person in uniquePeople)
{
    Console.WriteLine(person.Name + ", " + person.Age);
}
416 chars
16 lines

This will output:

main.cs
John, 20
Mary, 25
18 chars
3 lines

gistlibby LogSnag