linq查询重复列表中的列

时间:2013-05-23 09:30:02

标签: c# linq linq-to-objects generic-collections

我有一张类似下面的表格。

Branch      Dept        Product ID  Product Val Product Date
Branch 1        Dept 1      ID 1        1       5/23/2013
Branch 1        Dept 1      ID 2        1       5/23/2013
Branch 1        Dept 2      ID 3        1       5/23/2013
Branch 2        Dept 11     ID 4        1       5/23/2013
Branch 2        Dept 11     ID 5        1       5/23/2013
Branch 2        Dept 11     ID 6        1       5/23/2013
Branch 3        Dept 21     ID 7        1       5/23/2013

我正在尝试使用LINQ(作为LINQ的新手)将其作为对象集合加载到对象中,如:

Products = { Branch1 { Dept1 {ID1,ID2}, 
                       Dept2 {ID3}}, 
             Branch2 { Dept11 {ID4, ID5, ID6}}, 
             Branch3 { Dept21 {ID7 }
           }

我在一夜之间努力工作,但无法找到正确的解决方案。到目前为止,我已经实现了以下代码;

var branches = (from p in ProductsList
    select p.Branch).Distinct();
var products = from s in branches
    select new
    {
        branch = s,
        depts = (from p in ProductsList
            where p.Branch == s
            select new
            {
                dept = p.Dept,
                branch = s,
                prod = (from t in ProductsList
                    where t.Branch = s
                    where t.Dept == p.Dept
                    select t.ProductID)
            })
    };

其中ProductsList是整个表日期List

的列表对象

最早的帮助非常感谢。提前谢谢!

2 个答案:

答案 0 :(得分:0)

如果你真的想使用linq,我会去那样的东西。

有些时候,一些foreach更清楚了!

var myDic = ProductList
                .GroupBy(m => m.Branch)
                .ToDictionary(
                    m => m.Key,
                    m => m.GroupBy(x => x.Dept)
                          .ToDictionary(
                              x => x.Key,
                              x => x.Select(z => z.ProductId)));

结果将是

Dictionary<string, Dictionary<string, IEnumerable<string>>>

其中第一个词典键为Branch,内部词典键为Dept,字符串列表为ProductId

似乎与你想要的结果有关。

答案 1 :(得分:0)

这样的事,也许?

Products.
    .Select(prop => prop.Branch)
    .Distinct()
    .Select(b => new 
    {
        Branch = b,
        Departments = Products
            .Where(p => p.Branch == b)
            .Select(p => p.Dept)
            .Distinct()
            .Select(d => new 
            {
                Products = Products
                    .Where(p => p.Department == d)
                    .Select(p => p.ProductID)
                    .Distinct()
            })
    })