Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ C中的分组_C#_Linq - Fatal编程技术网

C# LINQ C中的分组

C# LINQ C中的分组,c#,linq,C#,Linq,我有一个场景,其中我得到一个具有以下值的数据表: UserId DeptId deptname DependentName 1 45 test test1 1 45 test test2 1 45 test test3 2 46 y firstName 2 46 y f

我有一个场景,其中我得到一个具有以下值的数据表:

 UserId   DeptId deptname  DependentName
  1          45     test       test1
  1          45     test       test2
  1          45     test       test3
  2          46     y          firstName
  2          46     y          firstName1
  2          46     y          firstName2
我需要一个LINQ查询,其中我需要获得一个以下格式的查询:

user id = 1
deptid = 45 
deptname = test

DependentName = {test1,tes2,test3}

user id = 2
deptid = 46 
deptname = y

DependentName = {firstName,firstName1,firstName2}
什么是问题

var result = ctx.Entity.GroupBy(u => new { 
   u.UserId,
   u.DeptId,
   u.DeptName
}).ToList().Select(grouped => new { 
    GroupKey = grouped.Key,
    DeptNames => string.Join(",", grouped.Select(gr => gr.DependentName)) 
});
基于MSDN:

public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
)
这里已经回答了这个问题:

因此,您希望将DependentName作为逗号分隔的字符串。我说的对吗?我打赌他根本没试过。如果他用谷歌搜索linq101,他就会得到答案。仅供参考。我试过,然后来帮助这个网站,但dependent的值不是分组,而是继续尝试。谢谢您的时间。GroupBy之后的ToList是多余的@MaciejLos否。如果是实体框架上下文,string.Join将在没有ToList的情况下失败。我使用datatable作为可枚举项,因此无法获取它而不是ToList。您可以使用可计算。谢谢,解决了我在从分组项中选择结果集时遗漏的问题。再次感谢
melist.GroupBy(e = > new { e.UserId, e.DeptId, e.Deptname }, e);