如何合并在 LINQ 中使用 group by 创建的子数据?
How to marge child data created by using group by in LINQ?
我 table 有以下数据。
我想按 DocumentID 对数据进行分组,然后使用逗号分隔符将 DocPropIdentifyName 和元值合并在一起。输出将如下所示:
我正在使用如下所示的 foreach 来完成此操作:
var test = (from r in lstDocSearch
group r by r.DocumentID
into g
select new
{
DocumentID = g.Key,
MetaValues = g.ToList()
}).ToList();
List<DocSearch> list = new List<DocSearch>();
foreach (var item in test)
{
foreach (var item2 in item.MetaValues)
{
var check = list.Exists(x => x.DocumentID == item2.DocumentID);
if (check)
{
var find = list.FirstOrDefault(x => x.DocumentID == item2.DocumentID);
find.MetaValue = find.MetaValue + ", " + item2.MetaValue;
find.DocPropIdentifyName = find.DocPropIdentifyName + ", " + item2.DocPropIdentifyName;
}
else
{
DocSearch objDocSearch = new DocSearch();
objDocSearch.DocumentID = item2.DocumentID;
objDocSearch.DocPropIdentifyID = item2.DocPropIdentifyID;
objDocSearch.DocPropIdentifyName = item2.DocPropIdentifyName;
objDocSearch.MetaValue = item2.MetaValue;
list.Add(objDocSearch);
}
}
}
但我想使用 linq 来执行此操作,而不是循环遍历集合。可能吗?
你的意思是这样的吗? :
var test = (from r in lstDocSearch
group r by r.DocumentID
into g
select new
{
DocumentID = g.Key,
MetaValues = String.Join(",", g.Select(o => o.MetaValue)),
DocPropIdentifyNames = String.Join(",", g.Select(o => o.DocPropIdentifyName)),
}).ToList();
我 table 有以下数据。
我想按 DocumentID 对数据进行分组,然后使用逗号分隔符将 DocPropIdentifyName 和元值合并在一起。输出将如下所示:
我正在使用如下所示的 foreach 来完成此操作:
var test = (from r in lstDocSearch
group r by r.DocumentID
into g
select new
{
DocumentID = g.Key,
MetaValues = g.ToList()
}).ToList();
List<DocSearch> list = new List<DocSearch>();
foreach (var item in test)
{
foreach (var item2 in item.MetaValues)
{
var check = list.Exists(x => x.DocumentID == item2.DocumentID);
if (check)
{
var find = list.FirstOrDefault(x => x.DocumentID == item2.DocumentID);
find.MetaValue = find.MetaValue + ", " + item2.MetaValue;
find.DocPropIdentifyName = find.DocPropIdentifyName + ", " + item2.DocPropIdentifyName;
}
else
{
DocSearch objDocSearch = new DocSearch();
objDocSearch.DocumentID = item2.DocumentID;
objDocSearch.DocPropIdentifyID = item2.DocPropIdentifyID;
objDocSearch.DocPropIdentifyName = item2.DocPropIdentifyName;
objDocSearch.MetaValue = item2.MetaValue;
list.Add(objDocSearch);
}
}
}
但我想使用 linq 来执行此操作,而不是循环遍历集合。可能吗?
你的意思是这样的吗? :
var test = (from r in lstDocSearch
group r by r.DocumentID
into g
select new
{
DocumentID = g.Key,
MetaValues = String.Join(",", g.Select(o => o.MetaValue)),
DocPropIdentifyNames = String.Join(",", g.Select(o => o.DocPropIdentifyName)),
}).ToList();