Check if list <t> contains any other list
I have a list of such parameters:
public class parameter { public string name {get; set;} public string paramtype {get; set;} public string source {get; set;} } IEnumerable<Parameter> parameters; And an array of strings that I want to check.
string[] myStrings = new string[] { "one", "two"}; I want to iterate over the parameter list and check if the source property matches any of the myStrings array. I can do this with a nested foreach, but I would like to know how to do it better, since I played with linq and, like extension methods, listed, for example, where, etc., so nested foreachs just feel like not this way. Is there a more elegant linq / lambda / delegete preferred way to do this.
thank
You can use nested Any() for this check, which is available on any Enumerable :
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x)); Faster execution in large collections would be to project parameters to source and then use Intersect , which internally uses a HashSet<T> , so instead of O (n ^ 2) for the first approach (equivalent to two nested loops) you can execute check O (n):
bool hasMatch = parameters.Select(x => x.source) .Intersect(myStrings) .Any(); Also, as a side comment, you should use class names and class names to match C # style styles.
Here is an example to find if there are matching items in another list
List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 }; List<int> nums2 = new List<int> { 1, 3, 6, 9, 12}; if (nums1.Any(x => nums2.Any(y => y == x))) { Console.WriteLine("There are equal elements"); } else { Console.WriteLine("No Match Found!"); } If both lists are too large, and when we use a lambda expression, the selection will take a lot of time. In this case, it is better to use linq to get a list of parameters:
var items = (from x in parameters join y in myStrings on x.Source equals y select x) .ToList();