无法将
DisplayMemberPath="Source"
类型隐式转换为DisplayMemberPath="Key"
。存在显式转换(您是否错过了演员?)
我有两个名为Data2的数据表,Data3, 我希望在分组后将数据输入到Data3中。 如何修改我的代码?
'System.Collections.Generic.List<AnonymousType#1>'
答案 0 :(得分:4)
投影:
select new
{
ID = g.Key.ID,
StyleID = g.Key.StyleID,
BrandID = g.Key.BrandID,
SeasonID = g.Key.SeasonID,
Article = g.Key.Article,
PatternCode = g.Key.PatternCode,
QTY = g.Sum(p => p.Field<int>("QTY"))
}
表示您正在创建每行,匿名类型的实例(由编译器生成的类); 不 a DataRow
。因此,当您.ToList()
时,您会得到List<T>
,其中T
是匿名类型。您可以var temp = ...
将列表分配给某些内容,但它仍然与DataRow
无关。你需要(其中之一):
DataTable
/ DataRow
(严重的是,它们非常糟糕;其他任何东西都更可取)DataTable
答案 1 :(得分:1)
试试这个:
var temp = (from p in Data2.AsEnumerable()
group p by new
{
ID = p.Field<string>("ID"),
StyleID = p.Field<string>("StyleID"),
BrandID = p.Field<string>("BrandID"),
SeasonID = p.Field<string>("SeasonID"),
Article = p.Field<string>("Article"),
PatternCode = p.Field<string>("PatternCode")
} into g
select new
{
ID = g.Key.ID,
StyleID = g.Key.StyleID,
BrandID = g.Key.BrandID,
SeasonID = g.Key.SeasonID,
Article = g.Key.Article,
PatternCode = g.Key.PatternCode,
QTY = g.Sum(p => p.Field<int>("QTY"))
}).ToList();
Data3 =ConvertToDataTable(temp);
public DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}