Merging two IEnumerables

前端 未结 3 1783
再見小時候
再見小時候 2020-12-09 01:20

I have two IEnumerables.

One gets filled with the fallback ellements. This one will always contain the most elements. The other one will get fi

相关标签:
3条回答
  • 2020-12-09 01:31

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

    0 讨论(0)
  • 2020-12-09 01:32

    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)));
    }
    
    0 讨论(0)
  • 2020-12-09 01:38
    translated.Union(fallback)
    

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

    translated.Union(fallback, PersonComparer.Instance)
    

    where PersonComparer is:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题