2015-09-25 93 views
1
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 

var pairs = 
    from a in numbersA 
    from b in numbersB 
    where a < b 
    select new { a, b }; 
+0

https://social.msdn.microsoft.com/Forums/en-US/190e1fdf-0b38-4d30-ac52-59c8d15f771a/c-possible-lambda-in-arrays-content-declaration?forum=csharplanguage – kevintjuh93

+0

possible [使用lambda類型的Init數組的副本](http://stackoverflow.com/questions/5368492/init-array-of-type-with-lambda) – kevintjuh93

+1

請參閱http://codeblog.jonskeet.uk/2011/01/28/reimplementing-linq-to-objects-part-41-how-query-expressions-work /查詢表達式如何翻譯。 –

回答

3

你可以嘗試這樣的事:

var pairs = numbersA.SelectMany(a => numbersB.Where(b => b>a) 
        .Select(b => new { a, b })); 

請參閱本.NET Fiddle

什麼SelectMany

將序列的每個元素投影到IEnumerable並將產生的序列展平成一個序列。

SelectMany的結果是將包含 numbersB陣列,其比 a更大所有當前 a和所有的數字之間的組合

所以,我們選擇一個匿名類型具有兩個屬性,ab 。對numbersA中的所有數字執行此操作,我們就會得到我們想要的。