如何在LINQ中使用group by创建子数据?

时间:2016-03-28 10:41:42

标签: c# linq linq-to-sql group-by linq-to-entities

我列出了以下数据。

enter image description here

我想按DocumentID对数据进行分组,然后想要使用逗号分隔符将DocPropIdentifyName和meta值组合在一起。输出如下:

enter image description here

我是通过使用下面的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做这个,而不是循环遍历集合。可能吗?

1 个答案:

答案 0 :(得分:2)

你是说这样的意思吗? :

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();