繁体   English   中英

linq查询列表中的重复列

[英]linq query repeated columns in a list

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

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是整个表格日期列表的列表对象

尽早提供任何帮助,将不胜感激。 提前致谢!

如果您真的想使用linq,我会做这样的事情。

Somethimes,一些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

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

这样的事,也许吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM