【问题标题】:Using Linq to create a collection of a custom class from a DbSet that contains a list of grouped entities使用 Linq 从包含分组实体列表的 DbSet 创建自定义类的集合
【发布时间】:2013-05-25 14:27:12
【问题描述】:

给定一个看起来像这样的数据集:

Iqueryable<photos> which represents the following table in a database

DataTable table = new DataTable("Trip");
table.Columns.Add("Date", typeof(string));
table.Columns.Add("Location", typeof(string));
table.Columns.Add("PhotoName", typeof(string));

table.Rows.Add("1/1/2001", "Home", "Photo1.jpg");
table.Rows.Add("1/1/2001", "Home", "Photo2.jpg");
table.Rows.Add("1/2/2001", "Work", "Photo3.jpg");
table.Rows.Add("1/2/2001", "Work", "Photo4.jpg");
table.Rows.Add("1/3/2001", "Home", "Photo5.jpg");

我想创建一个按日期和位置分组的以下类的集合:

 class PhotoCollection
 { 
      string date;
      string location;
      IList<string> namesOfPhotos;
 }

我从:

 from photo in photos
 group photo by new { photo.date, photo.location };

问题:

现在项目已经分组,是否可以整齐地创建内联 PhotoCollection 的集合?

【问题讨论】:

    标签: linq entity-framework collections


    【解决方案1】:

    你可以试试这样的:

    var result = from photo in photos
                 group photo by new { date, location } into grp
                 select new PhotoCollection {
                                             date = grp.Key.date,
                                             location = grp.Key.location,
                                             namesOfPhotos = grp.Select(p => p.PhotoName).ToList()
                                            }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      List<PhotoCollection> lst = 
                    from t in table.AsEnumerable()
                    group t by new { t.Field<string>("Location"), t.Field<string>("Date") }
                    into g
                    select new PhotoCollection
                    {
                       date = g.Key.Date,
                       location = g.Key.Location,
                       namesOfPhotos = g.Select(c => c.Field<string>("PhotoName")).ToList()
                    }
      

      有关如何使用 linq 查询数据表的更多信息,请查看here

      【讨论】:

        猜你喜欢
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-09
        • 1970-01-01
        • 2015-09-06
        相关资源
        最近更新 更多