Multicolumn LIST<T> - Finding duplicates of a one column based on another column

398 views Asked by At

I need to find the duplicate items of one column (Qty) based on another column (Priority). I have a List that contains the following data:

Priority  Product  Qty
0           a       10
0           b       20
1           c       50
1           d       20
1           e       50
1           f       10
1           g       20
1           h       10

I need to produce a sorted List<T> that contains only the duplicates in terms of Qty among the items with priority 0.

I.e. the resulting List<T> would contain:

Priority  Product  Qty
0           a       10
1           f       10
1           h       10
0           b       20
1           d       20
1           g       20

Is there a simple LINQ/Lambda expression for doing this?

3

There are 3 answers

1
BartoszKP On BEST ANSWER

Here is a solution with GroupBy:

var result = input
    .GroupBy(p => p.Qty)
    .Where(g => g.Any(p0 => p0.Priority == 0))
    .Where(g => g.Skip(1).Any())
    .SelectMany(g => g)
    .OrderBy(g => g.Qty);
0
nvoigt On

Assuming you have an enumerable container called list that contains elements with properties Priority, Product and Qty:

var orderedResult = list.Where(element => !list.Contains(x => x != element && x.Priority == element.Priority && x.Qty == element.Qty)).OrderBy(element => element.Qty).ThenBy(element => element.Priority);
1
Rubens Farias On

Try this:

static void Main(string[] args)
{
    var items = new List<Item>
    {
        new Item { Priority = 0, Product = "a", Qty = 10 },
        new Item { Priority = 0, Product = "b", Qty = 20 },
        new Item { Priority = 1, Product = "c", Qty = 50 },
        new Item { Priority = 1, Product = "d", Qty = 20 },
        new Item { Priority = 1, Product = "e", Qty = 50 },
        new Item { Priority = 1, Product = "f", Qty = 10 },
        new Item { Priority = 1, Product = "g", Qty = 20 },
        new Item { Priority = 1, Product = "h", Qty = 10 }
    };

    foreach (var group in items.Where  (i => i.Priority == 0)
                               .GroupBy(i => i, g => items
                               .Where  (t => t.Qty == g.Qty && 
                                             t.Product != g.Product)))
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(group.Key);                   // Priority == 0
        Console.ForegroundColor = ConsoleColor.Gray;
        foreach (var item in group.SelectMany(i => i))  // dups
            Console.WriteLine("\t{0}", item);
    }
}

class Item
{
    public int    Priority { get; set; }
    public string Product  { get; set; }
    public int    Qty      { get; set; }
    public override string ToString()
    {
        return String.Format("{0}\t{1}\t{2}",
                             this.Priority, this.Product, this.Qty);
    }
}