In this post I’ll show how you can combine unique items
of two List<string> and then Sort them with the help of LINQ.
Let’s take two List<string> contains employee names:
List<string> empNameList1 = new List<string>()
{
"Sandeep",
"Ashwani",
"Ashish" ,
"Saurav"
};
List<string> empNameList2 = new List<string>()
{
"Rahul",
"Sachin",
"Sandeep",
"Yuvraj"
};
|
As you can see one name is common in both employee lists,
so let’s write LINQ statement (using the Enumerable.Concat method) to get
unique names and then sort them and finally print all the sorted unique names
by looping through it.
// Concatenate Unique Names of
two List<string> and then sort.
var finalNameList =
empNameList1.Concat(empNameList2).Distinct().OrderBy(e => e);
//Print sorted unique names.
foreach (var name in finalNameList)
Console.WriteLine(name);
|
great trick.
ReplyDeletewe can also use "Union()" method to find unique records from both collection.
var result = empNameList1.Union(empNameList2);
Thanks