Merging two IEnumerables

前端 未结 3 1793
再見小時候
再見小時候 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:38

    translated.Union(fallback)
    

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

    translated.Union(fallback, PersonComparer.Instance)
    

    where PersonComparer is:

    public class PersonComparer : IEqualityComparer
    {
        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;
        }
    }
    

提交回复
热议问题