Jeremy Thompson
Jeremy Thompson

Reputation: 65672

Convert a IEnumerable<AnonymousType#1> to List<string>

I want a List<string> containing all the 'selected' series codes from this DataGridView:

enter image description here

I can get them as DataGridViewRow's, eg:

List<DataGridViewRow> selectedSeriesCodes =
                gridSeriesList.Rows.Cast<DataGridViewRow>().Where(g =>
                    !string.IsNullOrEmpty(g.Cells[ListDataSource.gridColumn1].Value.ToString()) &&
                    Convert.ToBoolean(g.Cells[ListDataSource.gridColumn1].Value) == true).ToList();

But I am aiming to get them as a List<string> purely for separation of concerns as I dont want to pass controls into business logic to ease testing, and just a fyi this is a excel vsto add-in.

I thought using LINQ with an anon type would do the trick, but it wont compile, eg:

List<string> selectedSeriesCodes = from x in gridSeriesList.Rows.Cast<DataGridViewRow>()
                                       where (!string.IsNullOrEmpty(x.Cells[ListDataSource.gridColumn1].Value.ToString()) &&
                                        Convert.ToBoolean(x.Cells[ListDataSource.gridColumn1].Value) == true)
                                       select new { SeriesCode = x.Cells[ListDataSource.gridColumn2].ToString() };

Error 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>'. An explicit conversion exists (are you missing a cast?)

I am sure this is possible, otherwise I'll just use a for loop.

Upvotes: 0

Views: 1514

Answers (1)

Diego
Diego

Reputation: 18359

You are missing .ToList() :

List<string> selectedSeriesCodes = 
(from x in gridSeriesList.Rows.Cast<DataGridViewRow>()
where !string.IsNullOrEmpty(x.Cells[ListDataSource.gridColumn1].Value.ToString() 
      &&  Convert.ToBoolean(x.Cells[ListDataSource.gridColumn1].Value) == true)
select x.Cells[ListDataSource.gridColumn2].ToString()).ToList();

Upvotes: 4

Related Questions