Search code examples
c#asp.net-mvclinqlinq-to-excel

Linq: select where in List<string>


Struggeling with some LinqToExcel filtering here...

Ive got a List<string> columnsToFilter that contains 9 strings, and with that i want to filter out the data for certain columns in a List<Row>, where Row contains the properties

IEnumerable<string> ColumnNames
Cell this[string columnName]

So: List<Row> has say 30 rows, each having 12 ColumnNames. Now i want to filter that List<Row> using List<string> columnsToFilter so that i end up with a List<Row> of 30 rows and 9 ColumnNames.

I can select the data for one column by quering the columnname:

var result = content.Select(m => m["Column1"]).ToList();

Now i want to filter the data based on a List of strings List<string> columnsToFilter. Whats the best way to achieve that?


Solution

  • I ended up doing this in two steps:

            foreach (var column in columnNumbers)
            {
                yield return data.Select(m => m[column].Value.ToString()).ToList();
            }
    

    Now I have the data I need, but with the rows and columns swapped, so i had to swap rows for columns and vice versa:

            for (int i = 1; i < rowCount; i++)
            {
                var newRow = new List<string>();
    
                foreach (var cell in list)
                {
                    newRow.Add(cell[i]);
                }
    
                yield return newRow;
            }