Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save itorian/21d4765a0f89618f37d923fbf0d3c178 to your computer and use it in GitHub Desktop.
Save itorian/21d4765a0f89618f37d923fbf0d3c178 to your computer and use it in GitHub Desktop.
Comparing two List<T> to find match in both list, 1st list only, 2nd list only that is Insersect, Minus and Minus Except
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
List<Items> list1 = new List<Items>();
list1.Add(new Items { name = "abc" });
list1.Add(new Items { name = "abd" });
list1.Add(new Items { name = "aef" });
list1.Add(new Items { name = "ref" });
list1.Add(new Items { name = "eaf" });
List<Items> list2 = new List<Items>();
list2.Add(new Items { name = "abc" });
list2.Add(new Items { name = "exf" });
list2.Add(new Items { name = "sss" });
list2.Add(new Items { name = "eaf" });
// Find only in list1
List<Items> onlyInList1 = new List<Items>();
onlyInList1 = list1.Where(x => !list2.Any(y => y.name == x.name)).ToList();
Console.WriteLine("Only in list1 :-");
foreach(var i in onlyInList1)
{
Console.WriteLine(i.name);
}
// Find only in list2
List<Items> onlyInList2 = new List<Items>();
onlyInList2 = list2.Where(x => !list1.Any(y => y.name == x.name)).ToList();
Console.WriteLine("Only in list2 :-");
foreach (var i in onlyInList2)
{
Console.WriteLine(i.name);
}
// Find matched in both list
List<Items> equal = new List<Items>();
equal = list2.Where(x => list1.Any(y => y.name == x.name)).ToList();
Console.WriteLine("Matched in both lists :-");
foreach (var i in equal)
{
Console.WriteLine(i.name);
}
Console.ReadKey();
}
}
public class Items
{
public string name { get; set; }
}
}
@itorian
Copy link
Author

itorian commented Apr 13, 2016

Output here

output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment