我需要撤回所有在itemId和itemTypeId上都具有相同记录的记录。所以这应该带回来:
Frank M,Max Terry和John M,因为他们两个的itemId / ItemTypeId均为6/7和4/7。
项目是:
我有这个,但是不起作用:
return returnList
.GroupBy(x => new { x.ItemId, x.ItemTypeId })
.Where(g => g.Count() > items.Count - 1)
.Select(z => z.FirstOrDefault())
.ToList();
我应该能够按项目类型ID进行分组,然后获取项目组ID和项目ID中的所有用户。因此,如果用户同时拥有4/7和6/7,他们应该会出现。
编辑:
下面的代码返回正确的计数和正确的项目,但随后将其重复。 示例:
我只想要这个:
return returnList
.GroupBy(x => new { x.ItemId, x.ItemTypeId })
.Where(g => g.Count() > 1)
.SelectMany(g=>g)
.ToList();
答案 0 :(得分:0)
return returnList
.GroupBy(x => new { x.ItemId, x.ItemTypeId })
.Where(g => g.Count() > 1)
.SelectMany(g=>g)
.ToList();
编辑(重复):
我想这是因为对于组(x.ItemId,x.ItemTypeId),可以多于一行具有相同首字母的行。您可以使用其他分组或“区别”。
var userItems = new[] {
new UserItem(926, 1, "TaylorFrank", 6, 7),
new UserItem(839, 2, "Jonathan M", 4, 7),
new UserItem(933, 2, "Jonathan M", 6, 7),
new UserItem(689, 3, "Max Terry", 4, 7),
new UserItem(925, 3, "Max Terry", 6, 7),
new UserItem(932, 4, "Frank M", 4, 7),
new UserItem(931, 4, "Frank M", 6, 7),
new UserItem(691, 5, "Stephanie K", 4, 7),
new UserItem(809, 14, "Kevin McCannon", 4, 7),
//duplication for group (x.ItemId, x.ItemTypeId )
new UserItem(1926, 1, "TaylorFrank", 6, 7),
new UserItem(1839, 2, "Jonathan M", 4, 7),
new UserItem(1933, 2, "Jonathan M", 6, 7),
new UserItem(1689, 3, "Max Terry", 4, 7),
new UserItem(1925, 3, "Max Terry", 6, 7),
new UserItem(1932, 4, "Frank M", 4, 7),
new UserItem(1931, 4, "Frank M", 6, 7),
new UserItem(1691, 5, "Stephanie K", 4, 7),
new UserItem(1809, 14, "Kevin McCannon", 4, 7),
};
var groupedByItemAndType =
userItems
.GroupBy(x => new { x.ItemId, x.ItemTypeId })
.Where(g => g.Count() > 1);
var distinctUsersInGroup =
groupedByItemAndType
.Select(g => new { g.Key, distinctUsers = g.Select(ui => ui.Initials).Distinct() });
foreach(var item in distinctUsersInGroup)
{
Console.WriteLine($"group: {item.Key}, {string.Join("; ", item.distinctUsers)}");
}
答案 1 :(得分:0)
SelectMany是键,并按UserId分组
return returnList.GroupBy(x => new { x.UserId })
.Where(g => g.Count() > Items.Count - 1).SelectMany(x => x).ToList();