Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以将同一对象添加到LINQ中的多个组中吗?_C#_.net_Linq_Group By - Fatal编程技术网

C# 我可以将同一对象添加到LINQ中的多个组中吗?

C# 我可以将同一对象添加到LINQ中的多个组中吗?,c#,.net,linq,group-by,C#,.net,Linq,Group By,我有一组要在Linq中分组的对象。但是,我要使用的键是多个键的组合。例如 Object1: Key=SomeKeyString1 Object2: Key=SomeKeyString2 Object3: Key=SomeKeyString1,SomeKeyString2 现在我只希望结果是两组 Grouping1: Key=SomeKeyString1 : Objet1, Object3 Grouping2: Key=SomeKeyString2 : Object2, Object3

我有一组要在Linq中分组的对象。但是,我要使用的键是多个键的组合。例如

Object1: Key=SomeKeyString1

Object2: Key=SomeKeyString2

Object3: Key=SomeKeyString1,SomeKeyString2
现在我只希望结果是两组

Grouping1: Key=SomeKeyString1 : Objet1, Object3

Grouping2: Key=SomeKeyString2 : Object2, Object3
基本上,我希望同一个对象成为两个组的一部分。在林克有可能吗

好的,不要直接使用
GroupBy
GroupJoin
。这两种方法都从对象中提取单个分组键。但是,您可以执行以下操作:

from groupingKey in groupingKeys
from item in items
where item.Keys.Contains(groupingKey)
group item by groupingKey;
示例代码:

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);
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
类项目
{
//通常不要将字段公开!
公共只读列表键=新列表();
公共字符串名称{get;set;}
}
课堂测试
{
静态void Main()
{
var groupingKeys=新列表{“Key1”,“Key2”};
var items=新列表
{
新项{Name=“Object1”,键={“Key1”},
新项{Name=“Object2”,键={“Key2”},
新项{Name=“Object3”,键={“Key1”,“Key2”},
};
var query=来自groupingKey中的groupingKey
从项目中的项目
其中item.Keys.Contains(groupingKey)
按groupingKey对项目进行分组;
foreach(查询中的var组)
{
WriteLine(“Key:{0}”,group.Key);
foreach(组中的var项目)
{
Console.WriteLine(“{0}”,item.Name);
}
}
}
}