繁体   English   中英

从列表 A 中获取项目,其中 Id 在列表 A 和列表 B 中都很常见,并且该 ID 的计数器在列表 A 或列表 B 中大于 1

[英]Get items from List A where Id is common in both List A and List B and counter of that Id is more than 1 in List A or List B

我想从 ListA 中获取项目,其中两个列表中的 Id 值相同,并且 Id 的计数在列表 A 或列表 B 中必须大于 1

var items = itemsA.Where(x => itemsB.Select(y => y.Id == x.Id).Count() > 1);

这给我的结果是 itemsB 中的相同 ID 大于 1,我想使用 or 条件来检查 itemsA 中的相同计数器

Eg 1:
ListA=[{"id"=1,"name="abc"},{"id=1, "name"="def"}]
ListB=[{"id=2","name="xyz"}, {"id=1, "name"="mno"}]
Should return [{"id"=1,"name="abc"},{"id=1, "name"="def"}] because id =1 exists in listB and the count of id with value 1 in listA is more then 1.
Eg 2:
ListA=[{"id"=2,"name="abc"},{"id=1, "name"="def"}]
ListB=[{"id=1","name="xyz"}, {"id=1, "name"="mno"}]


should return {"id=1, "name"="def"} because common id in both list is 1 and the count of id with value 1 in ListB is more then 1.

我不确定这是最好的解决方案,但据我了解这个问题,它应该是一个解决方案。

假设你有一个Item class 如下:

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

并将itemsAitemsB定义为List<Item> s,您可以首先找到两个列表中都存在的所有Id s,然后根据任一列表中每个Id的出现从itemsA中找到适用的项目 select:

IEnumerable<int> idsInBothItemLists = itemsA
    .Select(a => a.Id)
    .Intersect(itemsB.Select(b => b.Id))
    .Distinct();

List<Item> items = itemsA
    .Where(a => idsInBothItemLists.Contains(a.Id))
    .GroupBy(a => a.Id)
    .Where(gr => 
        gr.Skip(1).Any() ||
        itemsB.Where(b => b.Id == gr.Key).Skip(1).Any())
    .SelectMany(gr => gr.Select(item => item))
    .ToList();

.Skip(1).Any() .Count() > 1具有相同的目的;它只是检查在跳过第一个项目后是否还有剩余的项目。)


从建议的项目 A 和itemsB中打印itemsA

foreach (var entry in items)
{
    Console.WriteLine(entry.Id + " " + entry.Name);
}

例如输入

var itemsA = new List<Item>
{
    new Item { Id = 1, Name = "abc" },
    new Item { Id = 3, Name = "def" },
    new Item { Id = 1, Name = "ghi" },
    new Item { Id = 2, Name = "jkl" }
};

var itemsB = new List<Item>
{
    new Item { Id = 2, Name = "xyz" },
    new Item { Id = 2, Name = "jkl" },
    new Item { Id = 1, Name = "mno" },
    new Item { Id = 3, Name = "pqr" }
};

1 个字母
1 吉
2 jkl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM