john
john

Reputation: 121

Finding whether an element available in GenericList

I have a string[] which contains value {"data1","data2","data3"}.

and i have a GenericList which contains

data2

data4

two records

i want to get the common datas which is avail in string[] and the genericList

Upvotes: 0

Views: 91

Answers (3)

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9265

Take a look at the Intersect extension method here

  string[] c1 = { "data1", "data2", "data3" };
  string[] c2 = { "data2", "data4" };

  IEnumerable<string> both = c1.Intersect(c2);

  foreach (string s in both) Console.WriteLine(s);

Will print data2.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

Assuming it's a List<string> and you're using .NET 3.5 or higher, you can use the Intersect method from LINQ to Objects:

var intersection = stringArray.Intersect(stringList);

Note that this will return a lazily-evaluated IEnumerable<string>. If you need it in an array or a list, call the relevant method:

var intersectionArray = stringArray.Intersect(stringList).ToArray();
// or
var intersectionList = stringArray.Intersect(stringList).ToList();

Also note that this is a set operation - so the result will not contain any duplicates, even if there is duplication of a particular element in both the original collections.

Upvotes: 2

Adriaan Stander
Adriaan Stander

Reputation: 166396

Have you tried something like

string[] s = {"data1", "data2", "data3"};
List<string> list = new List<string> { "data2", "data3" };
var commonList = list.Intersect(s);

Have a look at Enumerable.Intersect Method (IEnumerable, IEnumerable)

Upvotes: 5

Related Questions