多列LIST <t> - 根据另一列</t>查找一列的重复项

时间:2013-12-06 11:37:42

标签: c# linq lambda duplicates duplicate-data

我需要根据另一列(Qty)找到一列(Priority)的重复项。我有一个包含以下数据的列表:

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

我需要生成一个排序List<T>,其中只包含优先级为Qty的项目中0的重复项。

即。生成的List<T>将包含:

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

是否有一个简单的LINQ / Lambda表达式来执行此操作?

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

以下是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);

答案 2 :(得分:0)

假设您有一个名为list的可枚举容器,其中包含属性为Priority,Product和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);