如何合并2个列表<t>并在C#中删除重复值

我有两个列表,我需要在第三个列表中合并,并从列表中删除重复值。

这有点难以解释,所以让我来展示一个示例,说明代码的样子以及我想要的结果,在示例中,我使用的是int类型,而不是ResultAnalysisFileSQL类。

第一个_列表=[1,12,12,5]

第二个_列表=[12,5,7,9,1]

合并两个列表的

结果应为以下列表: 结果_列表=[1,12,5,7,9]

您会注意到,结果中包含第一个列表,其中包含两个“ 12 ”值,第二个_列表中包含额外的12、1和5值。

ResultAnalysisFileSQL类

[Serializable]
public partial class ResultAnalysisFileSql
{
public string FileSql { get; set; }


public string PathFileSql { get; set; }


public List<ErrorAnalysisSql> Errors { get; set; }


public List<WarningAnalysisSql> Warnings{ get; set; }


public ResultAnalysisFileSql()
{


}


public ResultAnalysisFileSql(string fileSql)
{
if (string.IsNullOrEmpty(fileSql)
|| fileSql.Trim().Length == 0)
{
throw new ArgumentNullException("fileSql", "fileSql is null");
}


if (!fileSql.EndsWith(Utility.ExtensionFicherosErrorYWarning))
{
throw new ArgumentOutOfRangeException("fileSql", "Ruta de fichero Sql no tiene extensión " + Utility.ExtensionFicherosErrorYWarning);
}


PathFileSql = fileSql;
FileSql = ObtenerNombreFicheroSql(fileSql);
Errors = new List<ErrorAnalysisSql>();
Warnings= new List<WarningAnalysisSql>();
}


private string ObtenerNombreFicheroSql(string fileSql)
{
var f = Path.GetFileName(fileSql);
return f.Substring(0, f.IndexOf(Utility.ExtensionFicherosErrorYWarning));
}




public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is ResultAnalysisFileSql))
return false;


var t = obj as ResultAnalysisFileSql;
return t.FileSql== this.FileSql
&& t.PathFileSql == this.PathFileSql
&& t.Errors.Count == this.Errors.Count
&& t.Warnings.Count == this.Warnings.Count;
}




}

有用于合并和删除重复项的示例代码吗?

189896 次浏览

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();


// ulist output : 1, 12, 5, 7, 9

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

Use Linq's Union:

using System.Linq;
var l1 = new List<int>() { 1,2,3,4,5 };
var l2 = new List<int>() { 3,5,6,7,8 };
var l3 = l1.Union(l2).ToList();
    List<int> first_list = new List<int>() {
1,
12,
12,
5
};


List<int> second_list = new List<int>() {
12,
5,
7,
9,
1
};


var result = first_list.Union(second_list);

Union has not good performance : this article describe about compare them with together

var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
dict[person.Number] = person;
}
var merged = dict.Values.ToList();

Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms