简体   繁体   中英

C# Linq DB table to List of Lists

I've got a DB table with three fields, Category, Name, and value (string, string, int). Category and Name together are the primary key. My intent now is to write a method to return the contents of this table sorted into a

List<List<string>>

where each List is a list of entries with the same category (and the first string is the category). How can I do this, or am I going about this the wrong way?

EDIT: The reason I've chose this data type is that I will be filling HTML tables with the data, and would just like to iterate with nested foreach loops.

foreach(List<string ls in List<List<string>>)
   use a foreach(string) to generate a table for ls

I think this would be better represented by

class foo{
    public string val1 {get;set;}
    public string val2 {get;set;}
    public int val3 {get;set;}
}

and then

List<foo>

...but that's just my interpretation of the data you've presented.

I have a feeling you are going about this the wrong way. I would create a simple class

class Item
{
    public string Category {get; set;}
    public string Name{get; set;}
    public string Value {get; set;}
}

and manage List<Item> instead.

List<List<string>> toListOfListOfString(Table table) 
{ 
  return table.Select(x=>new List<string>{x.Category,x.Name,x.Value.ToString()})
              .ToList();
}
  var table = new [] {new {Category="a", Name="name1"},new {Category="a", Name="name2"},new {Category="B", Name="name3"}};
  List<List<string>> x = 
     table
        .GroupBy(
           row => row.Category, 
           (k, rows) => new List<string> (new [] {k}.Union(rows.Select(r => r.Name))))
        .ToList ();

Of course, in your case you'll use your table instead of mine. ;-)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM