我可以同一个对象添加到多个组在LINQ? [英] Can I add same object to multiple groups in LINQ?
本文介绍了我可以同一个对象添加到多个组在LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组对象,我想组中的LINQ。不过,我想使用的关键是多个按键的组合。对于如
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
基本上我想相同的对象是两个群体的一部分。这有可能在LINQ的?
Basically I want the same object to be part of two groups. Is that possible in Linq?
推荐答案
哦,不是的直接的与 GROUPBY
或群组加入
。这两个的提取的对象的单个分组密钥。然而,你可以这样做:
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;
样品code:
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);
}
}
}
}
这篇关于我可以同一个对象添加到多个组在LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文