合并两个IEnumerable的< T> S [英] Merging two IEnumerable<T>s

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

问题描述

我有两个的IEnumerable< T> 取值

有的人变得充满后备ellements。这其中将始终包含大多数元素。
根据某些参数的另一个将得到填补,并可能包含较少的元素。
如果一个元素不存在于第二个存在,我需要与第一个相当于一个填充它。

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.

这code做工作,但感觉效率不高,我和要求我的IEnumerables转换为ILists或使用临时表
人实现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的&LT; T&GT; S的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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