Home > Enterprise >  Split a list based on another list c#
Split a list based on another list c#

Time:06-19

I have a list of strings like

List<string> mylist = new List<string> { "US", "UK" };

and another list variable contains the values like

List<string> countries = new List<string> { "US", "AU","NL" };

I just want to split the countries list into two based on my list

ex

list1 =  { "US"};
list2 =  {  "AU","NL" };

I tried to group the list but i failed. any help?

var results = mylist.GroupBy(item => countries.Contains(item)).ToList();
var list1 = results.First().ToList();  
var list2 = results.Last().ToList();

above code return the same mylist values for list1 and list2

CodePudding user response:

You can use this;

var mylist = new List<string>{ "US", "UK" };
        
var countries = new List<string>{ "US", "AU","NL" };

var list1 = mylist.Intersect(countries).ToList();
var list2 = countries.Except(mylist).ToList();
  • Related