【问题标题】:join two lists under condition在条件下加入两个列表
【发布时间】:2012-04-21 05:17:07
【问题描述】:

我有以下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSomethingRelatedToLINQ
{
    class Person : IEqualityComparer<Person>
    {
        internal int personID;
        internal string PersonName;


        public bool Equals(Person x, Person y)
        {
            return x.personID == y.personID;
        }
        public int GetHashCode(Person obj)
        {
            return obj.personID.GetHashCode();
        }


    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> list1 = new List<Person>{            
            new Person{personID = 1 , PersonName = "Ali"},
            new Person{personID = 2 , PersonName = "Ali1"},
            new Person{personID = 3 , PersonName = "Ali2"}            
            };

            List<Person> list2 = new List<Person>{            
            new Person{personID = 4 , PersonName = "Habib1"},
            new Person{personID = 2 , PersonName = "Habib2"},
            new Person{personID = 5 , PersonName = "Habib3"}            
            };           



        }
    }
}

我需要选择 list1 中的所有元素,并且 list2 中没有 personID 的所有元素都存在于 List1 中,然后按 personID 对结果进行排序

新的输出应该是这样的

1, Ali 
2, Ali1 
3, Ali2
4, Habib1
5, Habib3

知道如何使用它

【问题讨论】:

    标签: generics .net-3.5 c#-3.0


    【解决方案1】:

    首先调用 LINQ Concat,以便将列表 2 附加到列表 1。

    然后调用 LINQ Distinct,它将删除重复的条目(前者或后者)。

    This site建议你使用的类,你只需实现IEqualityComparer接口即可。

    【讨论】:

    • 非常感谢这个建议,我在修复它之后弄错了,效果很好
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多