Search code examples
c#linq

How to extract one kind of values from a list of object type


I am new to C#. I want to fetch data from database and group it( account numbers with their corresponding item numbers ), save it in a list and send it to some other function . In that function, I want to extract only numbers from that list and send those numbers one by one as a parameter of stored procedure for further processing(database update).

The issue I am facing is that I am not able to update the database.The control is going to Console.WriteLine("Failed").I believe the issue is in the foreach loop in the UpdatePrice function(Not sure if this is what is causing issue).

My Effort

My class ListItems is as below -

class ListItem
{
    public string Number { get; set; }

       public List<string> books{ get; set; }

       
    }

I am successfully able to fetch data from the database, group it and send it to UpdatePrice() -

 Number = (from result in dt.AsEnumerable() group result by result.Field<string>("Number") into g select new ListItem { number = g.Key, itemNumbers = g.Select(x => x.Field<string>("itemnumber")).ToList() }).ToList();

UpdatePrice(Number);

Solution

  • In UpdatePrice after your query, items contains an IEnumerable<List<string>>, so on each iteration item will be a List<string> not a string.

    You can flatten the graph using SelectMany:

    var items = accounts.Select(a => a.itemNumbers).SelectMany(i => i);