linq与合并列分组

时间:2019-03-20 19:57:24

标签: c# .net linq lambda

我的Object的数据如下所示

enter image description here

我正在寻找这样的结果

enter image description here

为此,我正在尝试使用下面的linq查询

 var results = (from l in res 
            group new
            {
                l.MDMChannelCallLetters,
                l.UserName,
                l.IsActive,
                l.IsLocal,
                l.IsNetwork,
                l.IsPrivate,                 
                l.RatecardDescription,
                l.RatecardName,
            } by l.RatecardId into g select new
            {
                // I am not sure what i need to do 

            } )

请问有人可以使用linq Query仅将具有相同ID的特定列值与逗号分隔结合起来吗?

非常感谢!

2 个答案:

答案 0 :(得分:1)

您必须首先按常用属性对其进行分组:

 var grouped = res.GroupBy(c => new {
      c.RatecardId,
      c.RatecardName,
      c.RatecardDescription,
      IsActive,
      IsPrivate,
      IsLocal,
      IsNetwork
 });

然后您需要选择最终结果。 像这样:

var results = grouped.Select(c => new {
     c.Key.RatecardId,
     c.Key.RatecardName,
     c.Key.RatecardDescription,
     c.Key.IsActive,
     c.Key.IsPrivate,
     c.Key.IsLocal,
     c.Key.IsNetwork,
     MDMChannelCallLetters = string.Join(", ", c.Select(x => x.MDMChannelCallLetters)),
     UserName = string.Join(", ", c.Select(x => x.UserName))
});

答案 1 :(得分:0)

因此Res是包含来自第一个表的行的序列。我不知道Res是什么,所以让我们定义一个元素是Re

如果有一系列项目,并且想要将它们分组为具有共同点的项目组,请使用Enumerable.GroupBy。如果序列在数据库中,并且为此使用了实体框架,则应使用Queryable.GroupBy。语法类似

GroupBy具有参数KeySelector,该参数定义组应具有的共同属性。它还有一个结果选择器:它选择每个组应包含的内容。

var groupedItems = res.GroupBy(re => re => new

// KeySelector: what should the elements of a group have in common
// = make groups of Res with same RateCardId, RateCardName, ..., MdmChannelCallLetters
{
     Id = re.RateCardId,
     Name = re.RateCardName,
     Description = re.RateCardDescription,
     ...
     MdmChannel = re.MdmChannelCallLetters,
},

// ResultSelector: take the Key (= what do they have in common,
// and all Res that have these values for key
// to make one new object:
(key, resWithThisKey) => new
{
    RateCardId = key.Id,
    RateCardName = key.Name,
    ...
    MdmChannelCallLetters = key.MdmChannel,

    // You want to concatenate the user names:
    UserNames = String.Join(',', resWithThisKey.Select(re => re.UserName)),
});

GroupBy有一个参数ElementSelector的重载,您可以在其中定义应该在组中的元素。这简化了您的ResultSelector:

var result = res.GroupBy( // KeySelector: see above

   // ElementSelector: what should the elements of each group be?
   // in your case: you want a group of UserNames
   re => re.UserName,

   // ResultSelector, similar as above, but now the elements of a group are the userNames
   (key, userNames) => new
   {
        RateCardId = key.Id,
        ...

        UserNames = String.Join('c', userNames),
   });