Question

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?

Was it helpful?

Solution 3

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

OTHER TIPS

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);

Define an object called MyObject which has the property names corresponding to the 9 columns that you want to select.

var excel = new ExcelQueryFactory("excelFileName");
var myObjects = from c in excel.Worksheet<MyObject>()
                       select c;

Bingo. You can now iterate through the 30 objects with the 9 columns as properties. Remember that LinqToExcel will happily fill objects even if they don't have all the columns represented.

You could even have a property or method as part of MyObject called "row" that would be a Dictionary() object so you could say myObject.row["ColumnName"] to reference a value if you preferred that syntax to just saying myObject.ColumnName to get the value. Personally I would rather deal with actual properties than to use the dictionary convolution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top