Search code examples
c#linqlistno-duplicates

Get a new result from a List


I have a detailed list and I want a new one with the elements of one property with no duplicates like this.

List<Class1> list = List<Class1>();
list.Add(new Class1("1", "Walmart", 13.54));
list.Add(new Class1("2", "Target", 12.54));
list.Add(new Class1("3", "Walmart", 14.54));
list.Add(new Class1("4", "BestBuy", 16.54));
list.Add(new Class1("5", "Walmart", 19.54));
list.Add(new Class1("6", "Amazon", 12.33));

My new list

List<Stores> newList = list.Select / FindAll / Group ?

I want this collection

newList = "Walmart", "Target", "BestBuy", "Amazon"

Solution

  • You need Distinct and Select.

    var newList = list.Select(x => x.Name).Distinct().ToList();
    

    If you also want your original class, you would have to get a bit more fancy.

    Either get MoreLINQ and use its DistinctBy method:

    var newList = list.DistinctBy(x => x.Name).ToList();
    

    Or use a clever GroupBy hack:

    var newList = list.GroupBy(x => x.Name).Select(x => x.First());