0

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

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 的列表对象

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

4

2 回答 2

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()
            })
    })
于 2013-05-23T09:41:06.400 回答
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

这似乎与您想要的结果相对应。

于 2013-05-23T09:37:49.267 回答