C#LINQ查询从不同层次结构中选择数据

时间:2013-12-09 09:30:10

标签: c# linq hierarchical

我有以分组形式排列的分层数据 - >子组 - >项目。 我想使用SelectMany

在一些有效的linq查询中转换以下代码片段
IEnumerable<MainGroup> res = <somedata containg hierarchy Groups -> SubGroups -> Items> ;
foreach (var group in res)
{
    foreach (var subgroup in group.SubGroups)
    {
        foreach (var item in subgroup.ItemMps)
        {
            if (item.ItemMpId.ToString() == work.ItemMpID)
            {
                temp = temp + group.MainGroupId + "," + subgroup.SubGroupId + "," +
                        item.ItemMpId + "-|-";
            }
        }
    }
}

请有人告诉我如何在这里使用linq查询。请注意,我的要求是使用SelectMany,我的最终输出需要具有所有层次结构级别的不同属性。

1 个答案:

答案 0 :(得分:1)

我认为你需要使用SelectMany的重载:

http://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx

但我也认为你需要两次打电话。鉴于以下结构,我想出了以下内容:

class Program
{
    static void Main(string[] args)
    {
        var groups = new List<Group>();

        var items = groups
            .SelectMany(group => group.SubGroups, (group, subGroup) => new
                {
                    group,
                    subGroup
                })
            .SelectMany(anon => anon.subGroup.Items, (anon, item) => new
                {
                    Group = anon.group,
                    SubGroup = anon.subGroup,
                    Item = item
                });

        Console.Read();
    }
}

class Group
{
    public string GroupName { get; set; }
    public List<SubGroup> SubGroups { get; set; }
}

class SubGroup
{
    public string SubGroupName { get; set; }
    public List<Item> Items { get; set; }
}

class Item
{
    public string ItemName { get; set; }
}

基本上,您向前投影以保留对父项的引用。在您的特定结构中,它看起来像这样:

var items = groups
    .SelectMany(group => group.SubGroups, (group, subGroup) => new
        {
            group,
            subGroup
        })
    .SelectMany(anon => anon.subGroup.Items, (anon, item) => new
        {
            anon.group.MainGroupId,
            anon.subGroup.SubGroupId,
            item.ItemMpId
        });

这为您提供了一个当前未过滤的匿名类型的大型列表,如果您想要过滤这些内容,只需将Where调用附加到Items合并:

var items = groups
    .SelectMany(group => group.SubGroups, (group, subGroup) => new
        {
            group,
            subGroup
        })
    .SelectMany(anon => anon.subGroup.Items.Where(item => item.ItemMpId == work.ItemMpId), (anon, item) => new
        {
            anon.group.MainGroupId,
            anon.subGroup.SubGroupId,
            item.ItemMpId
        });

这应该符合您对SelectMany用法的要求,但是,我不相信这完全可读。

相关问题