我要在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);
}
}
}
}