Maximus Decimus
Maximus Decimus

Reputation: 5261

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"

Upvotes: 1

Views: 107

Answers (4)

Kevin DeVoe
Kevin DeVoe

Reputation: 602

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

Upvotes: 0

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

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

Upvotes: 3

SLaks
SLaks

Reputation: 887305

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

Upvotes: 2

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

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

Upvotes: 3

Related Questions