在T-SQL中,您可以使用CROSS APPLY
从表中获得左右表之间所有可能的差异。现在,我在C#
中遇到以下情况,我希望有一种方法可以使用LINQ到对象来解决我的问题。交叉应用 - LINQ到对象
我有TestData
对象(如下面)的列表,其类似于KeyValuePair<string, object>
对象(只是Key
和Value
属性): 键可以是一切,可以有具有相同键的多个对象。
IList<KeyValuePair<String, Object>> objects;
// Content of list
// # | Key | Value
// 1 | "A" | 1
// 2 | "A" | 2
// 3 | "A" | 3
// 4 | "B" | 4
// 5 | "B" | 5
// 6 | "C" | 6
// 7 | "D" | 7
// 8 | "D" | 8
我还请键列表:
IList<String> requestedKeys = new List<string>() { "A", "D" };
现在我想有在requestedKeys
列表中的键之间KeyValuePair对象的所有可能的组合。
IList<IList<KeyValuePair<String, Object>>> result = ...
// Content of 'result' will be in this example 6 lists with each 2 KeyValuePair objects
// # | "A" | "D" | (If there are more in the requestedKey list then there are more KeyValuePair items in the innerlist.)
// 1 | 1 | 7 |
// 2 | 2 | 7 |
// 3 | 3 | 7 |
// 4 | 1 | 8 |
// 5 | 2 | 8 |
// 6 | 3 | 8 |
是否有可能使用LINQ-to-Objects解决我的问题。如果不是,你能否告诉我反正建立它的最有效的方法。
编辑1:
为了更清楚的结果应该是什么:
我想有一个LINQ到对象查询是这样的:
@Joanna感谢在末端多个from
s,但问题是:使用此语法,您不能有动态数量from
s。在我来说,我需要尽可能多的from
S作为在requestedKeys
列表项
var result =
from listA in objects.Where(m => m.Key == "A")
from listD in objects.Where(m => m.Key == "D")
// from .....
// from .....
// overhere as many froms as items in 'requestedKeys' list
select new [] { listA, listD /*, All other lists */ }
的http://博客。 msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx –
那么,@乔安娜的回答有什么问题? (和你的编辑?) – leppie
@leppie它不够动态。例如,如果我请求所有可能的A B和C组合,那么你需要在结果列表中有第三个'from'和第三个KeyValuePair。所以我想知道如何使它变得动态。 – hwcverwe