在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