开发者

How to get a set of values as a list when grouped by a pair of columns

开发者 https://www.devze.com 2023-04-09 15:42 出处:网络
I have a datatable with below values idNamedate 1a5/3/2011 开发者_开发知识库1a6/4/2011 I want to retrieve the values with a list of associated dates for each id/name pair. I would suggest you crea

I have a datatable with below values

id Name date

1 a 5/3/2011

开发者_开发知识库

1 a 6/4/2011

I want to retrieve the values with a list of associated dates for each id/name pair.


I would suggest you create a class which encapsulates all of that data, and then you can create a List<T> of the appropriate type. You'd create an instance of your new class per entry in the DataTable.

If you use a strongly-typed dataset you could use the generated DataRow type instead, if you wanted.

(It's not clear what you mean by "store in a list as single entry" - the whole table, or one entry per row?)


It's difficult to answer with out the context of the usage. Is this going to be used right a way, communicated to other parts of the system. The below assumes that it's not coomunicated to other parts of the system

var list = (from e in DataTable.Rows.AsEnumerable()
            select new {
               id = e["id"],
               Name = e["Name"], 
               data = e["data"]
             }).ToList()


Create a class that maps onto your table. You can use EntityFramework, LINQ to SQL, nHibernate or a custom ORM to retrieve data from the table as these objects. Select the objects and use the LINQ grouping operator to either create anonymous objects (or another class with the list of dates).

public class Foo
{
   public int ID { get; set; }
   public sring Name { get; set; }
   public DateTime Date { get; set;
}

public class Bar
{
   public int ID { get; set; }
   public string Name { get; set; }
   public List<DateTime> Dates { get; set; }
}

public class FooDataContext : DbContext
{
   IDbSet<Foo> Foos { get; set; }
}

using (var context = new FooDataContext())
{
     List<Bar> bars = context.Foos
                             .GroupBy( f => new { f.ID, f.Name } )
                             .Select( g => new Bar
                              {
                                  ID = g.Key.ID,
                                  Name = g.Key.Name,
                                  Dates = g.Select( f => f.Date )
                              });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号