this-Me
this-Me

Reputation: 2145

Finding duplicate texts in IEnumerable<TextBox> collection

I have a collection of textboxes in my winform application.

I need help with LINQ query to get the collection of TextBox (i.e. IEnumerable) which contain duplicate entries.I want to make use of LINQ. This query I used, is returning just the duplicate entry. But I need all the duplicate entries.

var duplicates = emailAddressList.GroupBy(t => t.Text)
                        .Where(g => !string.IsNullOrEmpty(g.Key))
                        .SelectMany(grp => grp.Skip(1))
                        .ToList();

Can any one help where am I going wrong ?

Regards

Upvotes: 0

Views: 107

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

This query I used, is returning just the duplicate entry. But I need all the duplicate entries.

Check if g.Count() > 1 and use SelectMany(g => g) to get all of each duplicate-group instead of only the duplicates (without first).

var duplicates = emailAddressList
  .GroupBy(t => t.Text)
  .Where(g => !string.IsNullOrEmpty(g.Key) && g.Count() > 1)
  .SelectMany(g => g)
  .ToList();

Upvotes: 3

Related Questions