Search code examples
c#linqlinq-to-sqlado.net

How to convert IEnumerable type to List type?


I am trying to fetch certain database values and store them in a datatable. After that I am applying linq to group by all the data with account number.

I am getting the following error

Cannot implicitly convert type


Solution

  • Try this:

    class ListItem
    {
        public string accountNumber { get; set; }
         
        public List<string> itemNumbers { get; set; }
    }
    
    accounts = (from result in dataTable.AsEnumerable() group result by result.Field<string>("accountNumber") into g select new ListItems { accountNumber = g.Key, itemNumbers = g.Select(x => x.Field<string>("<itemNumber>")).ToList() }).ToList();
    

    An explanation is in order:

    1. I changed your ListItems class to ListItem and the itemNumbers property to be of type List<string>
    2. I am grouping all items (, I don't know the name of the column in your database) to a single ListItem instance, grouped by the accountNumber column, and storing all items in the itemNumbers property