Question

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"
Was it helpful?

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());

OTHER TIPS

Lets assume that Class1 is defined as :

public class Class1
{
    string Id {get;set;}
    string Store {get;set;}
    double Price {get;set;}
}

You can have your result as:

var result = list.Select(x => x.Store).Distinct().ToList();

You want to use Select() to select a specific property of the items:

list.Select(c => c.Company);

This returns an IEnumerable<string>.

You would then want to call .Distinct().

newList = list.Select(x => x.Store).Distinct().ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top