【问题标题】:Intersecting Dictionary<string, List<Anime>> on a property of Anime class在 Anime 类的属性上相交 Dictionary<string, List<Anime>>
【发布时间】:2018-04-04 14:11:43
【问题描述】:

我有一个这样的对象

public class Anime 
{
    public Guid Id {get; set;}
    public DateTime? CreatedOn {get; set;}

}

然后我有一个列表字典,如

Dictionary<string, List<Anime>> myLists = new Dictionary<string, List<Anime>>();

我正在与所有列表相交,但我只想在动漫 ID 上进行交集,但仍然得到 List&lt;Anime&gt; 的结果,不知道如何专门强制它在 ID 上进行。这是我所拥有的:

myResult.AddRange(myLists.Values.Aggregate(new HashSet<Anime>(myLists.First().Value.ToList()), (h, e) =>
                        {
                            h.IntersectWith(e);
                            return h;
                        }));

有没有办法告诉它在 ID 属性上相交但仍然获得作为动漫列表的结果? (myResultList&lt;Anime&gt;)。

【问题讨论】:

  • 您希望得到什么结果?在字典中出现多次的动漫列表?或者字典中每个列表中出现的动漫列表?
  • 在所有列表中都具有相同 ID 的动漫列表。所以如果我有 n 个列表,ID 5 应该在所有列表中,那么我希望这个动漫添加到我的结果列表中。

标签: c# list dictionary array-intersect


【解决方案1】:

我认为列表不能包含多个具有相同 ID 的动漫。 这应该有效:

var result = myLists.Values.SelectMany(p => p)
                .GroupBy(a => a.Id)
                .Where(g => g.Count() == myLists.Values.Count)
                .Select(g => g.First());

【讨论】:

    【解决方案2】:

    在属性上相交的等价物是join

    myResult.AddRange(myLists.Values.Aggregate((a, l) => a.Join(l, am => am.Id, lm => lm.Id, (am, lm) => am).ToList()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多