C# 合并两个 IEnumerable<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/590991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:28:22  来源:igfitidea点击:

Merging two IEnumerable<T>s

c#merge

提问by Boris Callens

I have two IEnumerable<T>s.

我有两个IEnumerable<T>

One gets filled with the fallback ellements. This one will always contain the most elements. The other one will get filled depending on some parameters and will possibly contain less elements. If an element doesn't exist in the second one, I need to fill it with the equivalent one of the first one.

一个充满了后备元素。这将始终包含最多的元素。另一个将根据某些参数被填充,并且可能包含更少的元素。如果第二个元素中不存在元素,我需要用第一个元素的等效元素填充它。

This code does the job, but feels inefficient to me and requires me to cast the IEnumerables to ILists or to use a temporary list Person implements IEquatable

这段代码完成了这项工作,但对我来说效率低下,需要我将 IEnumerables 转换为 ILists 或使用临时列表 Person 实现 IEquatable

IEnumerable<Person> fallBack = Repository.GetPersons();
IList<Person> translated = Repository.GetPersons(language).ToList();

foreach (Person person in fallBack)
{
    if (!translated.Any(p=>p.equals(person)))
        translated.add(person);  
}

Any suggestions?

有什么建议?

采纳答案by JaredPar

Try this.

尝试这个。

public static IEnumerable<Person> SmartCombine(IEnumerable<Person> fallback, IEnumerable<Person> translated) {
  return translated.Concat(fallback.Where(p => !translated.Any(x => x.id.equals(p.id)));
}

回答by Jon Skeet

translated.Union(fallback)

or (if Person doesn't implement IEquatable<Person>by ID)

或(如果 Person 没有IEquatable<Person>通过 ID实现)

translated.Union(fallback, PersonComparer.Instance)

where PersonComparer is:

其中 PersonComparer 是:

public class PersonComparer : IEqualityComparer<Person>
{
    public static readonly PersonComparer Instance = new PersonComparer();

    // We don't need any more instances
    private PersonComparer() {}

    public int GetHashCode(Person p)
    {
        return p.id;
    }

    public bool Equals(Person p1, Person p2)
    {
        if (Object.ReferenceEquals(p1, p2))
        {
            return true;
        }
        if (Object.ReferenceEquals(p1, null) ||
            Object.ReferenceEquals(p2, null))
        {
            return false;
        }
        return p1.id == p2.id;
    }
}

回答by smenon

use Concat. Uniondoes not work in case List<dynamic>type

使用Concat. Union在 caseList<dynamic>类型中不起作用