2010-04-14 36 views
0

我有一個矩陣,IEnumerable<IEnumerable<int>>矩陣,例如:使用LINQ以陣列來篩選基於包含一個矩陣的行

{ {10,23,16,20,2,4}, {22,13,1,33,21,11 }, {7,19,31,12,6,22}, ... } 

和另一個數組:

int[] arr={ 10, 23, 16, 20} 

我要過濾矩陣的條件是我將矩陣的所有行都包含與arr相同數量的元素。

也就是說矩陣{10,23,16,20,2,4}中的第一行有4個來自arr的數字,這個數組應該與來自arr的4個數字的其餘行分組。

更好的使用linq,非常感謝!

+0

我按照我解釋的方式編輯了你的問題 - 請告訴我們,如果我不正確。 – 2010-04-15 21:42:28

回答

0

這爲我工作:

private static void Main(string[] args) 
{ 
    int[] searchNums = new int[] {10, 23, 16, 20}; 
    var groupByCount = from o in lists 
         group o by o.Count(num => searchNums.Contains(num)) into g 
         orderby g.Key 
         select g; 
    foreach(var grouping in groupByCount) 
    { 
     int countSearchNums = grouping.Key; 
     Console.WriteLine("Lists that have " + countSearchNums + " of the numbers:"); 
     foreach(IEnumerable<int> list in grouping) 
     { 
      Console.WriteLine("{{ {0} }}", String.Join(", ", list.Select(o => o.ToString()).ToArray())); 
     } 
    } 
    Console.ReadKey(); 
} 

private static List<List<int>> lists = new List<List<int>> 
{ 
    new List<int> {10, 23, 16, 20, 2, 4}, 
    new List<int> {22, 13, 1, 33, 21, 11}, 
    new List<int> {7, 19, 31, 12, 6, 22}, 
    new List<int> {10, 13, 31, 12, 6, 22}, 
    new List<int> {10, 19, 20, 16, 6, 22}, 
    new List<int> {10}, 
    new List<int> {10, 13, 16, 20}, 
}; 

輸出:
{22,13,1,33,21,11}
{:具有數字的0

解釋7,19,31,12,6,22}
列表中有1個數字:
{10,13,31,12,6,22}
{10}
只 列出具有的數字3:
{10,19,20,16,6,22}
{10,13,16,20}
列出具有數的4:
{10 ,23,16,20,2,4}

+0

要獲得額外的功勞,請將LINQ查詢中的'lists'更改爲'lists.AsParallel()' - ** BAM!**即時多線程! (僅限VS 2010) – 2010-04-15 21:50:46

+0

首先感謝您的出色幫助,但實際上int [] searchNums也是一個矩陣,如int [] [] cj = {{10,23,16,20}, {22,13, 1,33}, {7,19,31,12}},我應該怎麼做? 謝謝! – 2010-04-16 14:31:12

+0

那麼如果問題是一樣的,只需將它結合成一維數組即可... – 2010-04-16 14:57:35