Linq: select where in List<string>

stefjnl picture stefjnl · Oct 2, 2013 · Viewed 35.4k times · Source

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?

Answer

Dweeberly picture Dweeberly · Oct 2, 2013

Is this what you are looking for?

var colnames = new List<string>();
var rows = new Dictionary<string, object>();
var result = rows.Where(kv => colnames.Contains(kv.Key)).Select(kv => kv.Value);