Using LINQ to get all object with the same value property?

I have a list of items like this:

Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item3: Id=3, Name="Test2"

What I want to perform is to get reduced list like this:

Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"

So basically I want to have items that have the same value of given property. So all the items that have the same value of given property.

I have tried to Group them but I don’t know what to do next.

items.OrderBy(x => x.Name);

Edit to explain.

It seams that I did not understand the question. The Answer is expected but there is already a solution here:

Right answer!

Answer

Using this input …

Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item3: Id=3, Name="name3"
Item4: Id=4, Name="Test2"
Item5: Id=5, Name="name1"
Item6: Id=6, Name="name3"

… this gets all the items occurring more than once:

var result = items
    .GroupBy(x => x.Name)        // Group by name
    .Where(g => g.Count() > 1)   // Select only groups having duplicates
    .SelectMany(g => g);         // Ungroup (flatten) the groups

Result:

Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item5: Id=5, Name="name1"
Item3: Id=3, Name="name3"
Item6: Id=6, Name="name3"

… this gets all the items occurring more than once and renumbers them

var result = items
    .GroupBy(x => x.Name)        // Group by name
    .Where(g => g.Count() > 1)   // Select only groups having duplicates
    .SelectMany(g => g)          // Ungroup (flatten) the groups
    .Select((x, i) => new Item { Id = i + 1, Name = x.Name });

Result:

Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item3: Id=3, Name="name1"
Item4: Id=4, Name="name3"
Item5: Id=5, Name="name3"

Note that Select has an overload providing a zero-based index.

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>)

However, your example input is too simplistic, therefore it is difficult to say what you expect to happen in more complex cases.

If you want entries with a specific name:

string specificName = "name1";
var result = items
    .Where(x => x.Name == specificName);

Leave a Reply

Your email address will not be published. Required fields are marked *