我想在 Linq 中对一组对象进行分组。然而我想使用的键是多个键的组合。例如
Object1: Key=SomeKeyString1
Object2: Key=SomeKeyString2
Object3: Key=SomeKeyString1,SomeKeyString2
现在我希望结果只有两组
Grouping1: Key=SomeKeyString1 : Objet1, Object3
Grouping2: Key=SomeKeyString2 : Object2, Object3
基本上我希望同一个对象属于两个组。这在 Linq 中可能吗?
最佳答案
嗯,不是直接使用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);
}
}
}
}
关于c# - 我可以将同一对象添加到 LINQ 中的多个组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6806684/