如何将此linq组作为非查询表达式编写?

时间:2018-04-19 03:31:15

标签: c# .net linq

我有一组具有GroupId和UserId的组用户。我需要过滤掉集合中可能存在的任何重复的GroupId / UserId对象。如何编写非查询表达式GroupBy来过滤掉重复的行?以下示例改编自我在网上找到的一组示例,但我不清楚如何针对我的特定场景优化此代码:

var groupByResults = 
groupUsers.GroupBy(
    x => x.GroupId,
    x => x.UserId,
    (key, g) => new
    {
        [?] = key,
        [?] = g.ToList()
    }
);

3 个答案:

答案 0 :(得分:0)

如果您的数据类似于下面的列表,则可以按复合键进行分组,然后获取每个组中的第一个值。 OrderBy是可选的

var groupUsers = new List<dynamic>() { 
    new { groupId = 1, userId = 1, name = "a" },
    new { groupId = 1, userId = 1, name = "b" },
    new { groupId = 1, userId = 2, name = "c" }
    };

var result =  groupUsers
    .GroupBy(u => new { u.groupId, u.userId} )
    .Select(g => g.OrderBy(u => u.name).FirstOrDefault());

答案 1 :(得分:0)

找出重复的userId,groupId。

  1. GroupBy userId,groupId

  2. 计算是否有任何组项&gt; = 2

  3. SelectMany the collection

  4. 代码:

    var duplicatedUsers = groupUsers
        .GroupBy(gu => new { gu.UserId, gu.GroupId })
        .Where(g => g.Count() >= 2)
        .SelectMany(g => g)
    

答案 2 :(得分:0)

以下代码对您有所帮助,

class GroupUsers 
{
    public int GroupId {get;set;}
    public int UserId {get;set;}
}

public class Program
{
    public static void Main()
    {
    var groupUsers = new List<GroupUsers>() { 
    new GroupUsers{ GroupId = 1, UserId = 1},
    new GroupUsers{ GroupId = 1, UserId = 1},
    new GroupUsers{ GroupId = 1, UserId = 2},
    new GroupUsers{ GroupId = 1, UserId = 2},
    new GroupUsers{ GroupId = 1, UserId = 3},
    new GroupUsers{ GroupId = 1, UserId = 4},
    new GroupUsers{ GroupId = 1, UserId = 5},
    new GroupUsers{ GroupId = 1, UserId = 3}
    };

     var result1 =  groupUsers
                    .GroupBy(u => new { u.GroupId, u.UserId} )
                    .Where(g => g.Count()>=2) // check for duplicate value by checking whether the count is greater than or equal to 2.
                    .SelectMany(g=>g); // flatten the list

    foreach(var user in result1) // Iterate over the result
    {
        Console.WriteLine(user.GroupId +" "+user.UserId);
    }
    // Or
    var result2 =   from a in groupUsers
                    group a by new{a.GroupId, a.UserId} into grp
                    where grp.Count()>=2
                    from g in grp select new{g}

    foreach(var user in result2)
    {
        Console.WriteLine(user.g.GroupId +" "+user.g.UserId);
    }

    }
}