开发者

Using LINQ to filter rows of a matrix based on inclusion in an array

开发者 https://www.devze.com 2022-12-27 01:52 出处:网络
I have a matrix, IEnumerable<IEnumerable<int>> matrix, for example: { {10,23,16,20,2,4},{22,13,1,33,21,11 }, {7,19,31,12,6,22}, ... }

I have a matrix, IEnumerable<IEnumerable<int>> matrix, for example:

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

and another array:

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

I want to filter the matrix on the condition that I group all rows of the matrix which contain the same number of elements from arr.

That is to say the first row in the matr开发者_运维知识库ix {10,23,16,20,2,4} has 4 numbers from arr, this array should be grouped with the rest of the rows with 4 numbers from arr.

better to use linq, thank you very much!


This worked for me:

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},
};

Output:

Lists that have 0 of the numbers:
{ 22, 13, 1, 33, 21, 11 }
{ 7, 19, 31, 12, 6, 22 }
Lists that have 1 of the numbers:
{ 10, 13, 31, 12, 6, 22 }
{ 10 }
Lists that have 3 of the numbers:
{ 10, 19, 20, 16, 6, 22 }
{ 10, 13, 16, 20 }
Lists that have 4 of the numbers:
{ 10, 23, 16, 20, 2, 4 }

0

精彩评论

暂无评论...
验证码 换一张
取 消