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 storing the final result in a list which is of the following class type -
class ListItems
{
public string accountNumbers
{
get;
set;
}
public string itemNumbers
{
get;
set;
}
}
My code is:
List<ListItems> accounts = new List<ListItems>();
public void GetItems(int ID1, int ID2)
{
con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_FetchItems";
cmd.Parameters.AddWithValue("@id1", ID1);
cmd.Parameters.AddWithValue("@id2", ID2);
cmd.Connection = con;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
accounts = from result in dt.AsEnumerable()
group result by result.Field<string>("accountNumber");
}
I am getting the following error
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Linq.IGrouping<string, System.Data.DataRow>>' to 'System.Collections.Generic.List<PricingPractice.ListItems>
on line
accounts = from result in dt.AsEnumerable()
group result by result.Field<string>("accountNumber");
I even tried to convert this expression using ToList() but it is also not working.
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:
ListItems
class to ListItem
and the itemNumbers
property to be of type List<string>
ListItem
instance, grouped by the accountNumber
column, and storing all items in the itemNumbers
property
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.