Can I add same object to multiple groups in LINQ?

懵懂的女人 提交于 2019-12-24 01:03:06

问题


I have a set of objects I want to group in Linq. However the key I want to use is a combination of multiple keys. for eg

Object1: Key=SomeKeyString1

Object2: Key=SomeKeyString2

Object3: Key=SomeKeyString1,SomeKeyString2

Now I'd like the results to be only two groups

Grouping1: Key=SomeKeyString1 : Objet1, Object3

Grouping2: Key=SomeKeyString2 : Object2, Object3

Basically I want the same object to be part of two groups. Is that possible in Linq?


回答1:


Well, not directly with GroupBy or GroupJoin. Both of those extract a single grouping key from an object. However, you could do something like:

from groupingKey in groupingKeys
from item in items
where item.Keys.Contains(groupingKey)
group item by groupingKey;

Sample code:

using System;
using System.Collections.Generic;
using System.Linq;

class Item
{
    // Don't make fields public normally!
    public readonly List<string> Keys = new List<string>();
    public string Name { get; set; }
}

class Test
{
    static void Main()
    {
        var groupingKeys = new List<string> { "Key1", "Key2" };
        var items = new List<Item>
        {
            new Item { Name="Object1", Keys = { "Key1" } },
            new Item { Name="Object2", Keys = { "Key2" } },
            new Item { Name="Object3", Keys = { "Key1", "Key2" } },
        };

        var query = from groupingKey in groupingKeys
                    from item in items
                    where item.Keys.Contains(groupingKey)
                    group item by groupingKey;

        foreach (var group in query)
        {
            Console.WriteLine("Key: {0}", group.Key);
            foreach (var item in group)
            {
                Console.WriteLine("  {0}", item.Name);
            }
        }
    }
}


来源:https://stackoverflow.com/questions/6806684/can-i-add-same-object-to-multiple-groups-in-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!