0

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?

asked Jul 31, 2014 at 10:22
10
  • 2
    Well what are x and y meant to be? Your question is unclear at the moment... a full concrete example would be really useful. Commented Jul 31, 2014 at 10:23
  • @Vlad, x and y are values from some array? Commented Jul 31, 2014 at 10:24
  • @user2167382 they are strings Commented Jul 31, 2014 at 10:26
  • Assuming that .Descendants(string) is a method on m returning a collection, containing somethat that has a Value property/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? Commented Jul 31, 2014 at 10:27
  • @LasseV.Karlsen I have many linqs, so I want use method to nake my code cleaner. Commented Jul 31, 2014 at 10:28

4 Answers 4

3

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)))
}
answered Jul 31, 2014 at 10:26
Sign up to request clarification or add additional context in comments.

Comments

0

You could simply copy the method signature. Put your cursor on Descendants and hit F12.

answered Jul 31, 2014 at 10:25

Comments

0

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);
answered Jul 31, 2014 at 10:40

Comments

0

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)));
answered Jul 31, 2014 at 10:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.