2016-10-14 29 views
-4

如何使用LINQ從某些數組中獲得有序的元素對?例如, 我有:Descarte的數組元素的方差

int[] d = { 1, 2, 3 }; 

我需要:

{{1,1},{1,2},....,{3,3}}

我試過LINQ查詢,但它返回

{{1,1},{2,2},{3,3},{1,1},{2,2},{ 3,3},{1,1},{2,2},{3, 3}}

var pairs = d.SelectMany(a => d.Select(b => new[] { a, b })); 

請幫我找到我的錯誤。

+6

您所提供的代碼可以產生你自稱想要的序列,沒有序列你說它。 – Servy

+1

您是否在尋找https://en.wikipedia.org/wiki/Cartesian_product(其中涵蓋了很多問題,包括http://stackoverflow.com/questions/3093622/generating-all-possible-combinations)?由於@Serv代碼在帖子中似乎產生了你想要的結果... –

回答

1

像這樣:

var result = d.SelectMany(a => d, Tuple.Create) 
       .Where(c=> c.Item1 <= c.Item2).ToArray(); 
+1

這很漂亮 –

+0

@MatiasCicero但是OP沒有聲明他希望在第一項小於第二項的情況下配對,所以這會產生錯誤的輸出。 – Servy

+0

@Servy如果OP的代碼正常工作,爲什麼他應該問一個問題?根據他的帖子,我認爲他正在尋找一個組合,第一個項目是少於第二個或平等。 –

-1

此代碼的工作

 int[] d = { 1, 2, 3 }; 

     var query = (from elem1 in d 
        from elem2 in d 
        where elem1>= elem2 
        select elem1< elem2? new List<int>() { elem1, elem2 }: new List<int>() { elem2, elem1 } 
        ).Distinct().ToArray(); 
+0

這段代碼的工作,我已經測試,你有{{1,1},{1,2},...,{3,3}}結果 – Esperento57