0

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.

2
  • 1
    how would you do it without LINQ? Did you even tried anything to achieve this? Commented Dec 15, 2021 at 16:14
  • You are making it yourself difficult, because you store the data in columns, instead of rows. Storing it as rows makes it a lot easier. So try to swap the outerloop and innerloop Commented Dec 15, 2021 at 16:15

1 Answer 1

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?

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]));
Sign up to request clarification or add additional context in comments.

7 Comments

Did you noticed it is stored as columns? (not rows)
@JeroenvanLangen: I don't think so. I think OP is reading a CSV row by row and value by value and stores them in string-arrays
It would be easier to store them as rows, so you can select all rows which matches the criteria.
@JeroenvanLangen: But each string[] represents a row and contains all values
Tim Schmelter's solution worked after I switched the list populating code from columns to rows, as Jeroen van Langen proposed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.