I have many linq queries, only difference is values.
string x = "foo1";
string y = "foo2"
foo.Where(m => m.Descendants(x).Any(v => v.Value.Contains(y)))
How can I use x and y like a variable, maybe I need extract linq in another method and how it I can do?
4 Answers 4
Are you looking for something like this
public static IEnumerable<XElement> GetElements(this XElement foo, string x, string y)
{
return foo.Where(m => m.Descendants(x).Any(v => v.Value.Contains(y)))
}
Comments
You could simply copy the method signature. Put your cursor on Descendants and hit F12.
Comments
Personally I need a good reason to use XPath or Linq to do element parsing instead of deserializing XML to hard type class elements. Like Selman22 you can write extension method
public static class Extensions
{
public static IEnumerable<XElement> GetElements(
this XElement foo, string x, string y)
{
return foo.Where(m => m.Descendants(x).Any(v => v.Value.IndexOf(y)>-1))
}
}
After that you can use :
var item = foo.GetElements(x,y);
Comments
I found a good solve for my problem with lambda expressions, thanks @Selman22 for idea.
Func<IEnumerable<XElement>, string, string, IEnumerable<XElement>> functionSearch;
functionSearch = (l, x, y) => l.Where(m => m.Descendants(x).Any(v => v.Value.Contains(y)));
xandymeant to be? Your question is unclear at the moment... a full concrete example would be really useful.xandyare values from some array?.Descendants(string)is a method onmreturning a collection, containing somethat that has aValueproperty/field that returns something on which.Contains(y)will work, I fail to see what the problem is here. Does the code as posted work? If so, what is the question?