7

Suppose I have the following class:

public class Test{
    public string Length { get; set; }
    public string Width { get; set; }
    public string Height { get; set; }
    public int Count { get; set; }
    public string Label { get; set; }
}

And I would like to find items that have the same value for length and label and counting how many there are for each. So far my code looks like:

var dups = testlist.GroupBy(i => new { i.Length, i.Label })
                   .Where(g => g.Count() >= 1)
                   .Select(g => new { Length = g.Key.Length, Label = g.Key.Label, 
                                      Count = g.Count() });

But the problem is, the objects in var no longer have the width or height property (they don't exist in g.Key). Is there anyway to find duplicates based on two properties while saving other properties in the result?

4
  • 1
    Since each group may have multiple items in it with different widths and heights, which values do you want? Commented Oct 23, 2012 at 14:58
  • 1
    Like in SQL you'd have to choose which ones to take after the grouping. Try g.First() to get the first Width or Height in the grouping. Commented Oct 23, 2012 at 14:59
  • 2
    (Also the Where clause is redundant - if there're no items with a given label and height, there won't be a group for them anyway.) Commented Oct 23, 2012 at 15:07
  • So do you want a list/collection of all of the width/heights, do you want the average, first, sum, max, last minimum, or what? Commented Oct 23, 2012 at 15:23

1 Answer 1

18

After this

testList
  .GroupBy(i => new { i.Length, i.Label })
  .Where(g => g.Count() >= 1)

you effectively have an IEnumerable<IEnumerable<Test>>. That's a list of lists of dupes. What more do you want?

Sign up to request clarification or add additional context in comments.

2 Comments

+1 and thanks for reminding me about compiler support for anonymous types.
Sorry I think I asked the question without thinking it through. Thanks for the answer though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.