合并两个 IEnumerable<T> [英] Merging two IEnumerable&lt;T&gt;s

查看:56
本文介绍了合并两个 IEnumerable<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 IEnumerable.

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

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.

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

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

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);  
}

有什么建议吗?

推荐答案

试试这个.

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)));
}

这篇关于合并两个 IEnumerable<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆