Home > Software engineering >  C# LINQ select from list of arrays of strings
C# LINQ select from list of arrays of strings

Time:12-16

I have this data

enter image description here

which is retained in a list of arrays of strings: List<string[]> arrData = new List<string[]>();. The list is filled with the following code:

int columnsCount =4;
int rowsCount = 6;
for (int j = 0; j < columnsCount; j  )
{
    string[] columnData = new string[rowsCount];
    for (int i = 0; i < rowsCount; i  )
        columnData[i] = csv[i][j];
    arrData.Add(columnData);
}

csv[i][j] gives the value for r1c1 etc., so in the end the list has 4 arrays elements, each array having 6 values.

  1. How can I use LINQ to select the yellow rows, meaning that have "a" in the first array, "g" in the second one and "m" in the third?
  2. How can I use LINQ to filter by a list of values in one column (meaning select all rows with "a" or "b" in first column)?

I can alter the code and create a list of lists / dictionaries / whatever is more suitable.

CodePudding user response:

How can I use LINQ to select the yellow rows, meaning that have "a" in the first array, "g" in the second one and "m" in the third?

IEnumerable<string[]> result = arrData
    .Where(arr => arr?.Length > 2 && arr[0] == "a" && arr[1] == "g" && arr[2] == "m");

How can I use LINQ to filter by a list of values in one column (meaning select all rows with "a" or "b" in first column)?

string[] firstColSearch = { "a", "b" };
IEnumerable<string[]> result = arrData
  .Where(arr => arr?.Length > 0 && firstColSearch.Contains(arr[0]));
  • Related