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内联集合?
答案 0 :(得分:0)
您可以尝试以下方式:
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()
}
答案 1 :(得分:0)
试试这个:
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