7

I have the following code sample in C# demonstrating how I would like to parse some of a LINQ query into a function's argument.

public List<object> AllElements;

public object GetAll<T>(SomeLINQQuery) {

    //get some elements from AllElements where the argument is added to the query, as shown below.

}

And now, to give this some meaning, what I was thinking of accomplishing would be this:

public void test() {
    GetAll<object>(where object.ToString() == "lala");
}

It's kind of hard to explain. I hope this example does it well.

2
  • 1
    I like that you provide a use-case. If there's a use case, there's usually code that can be written that makes the whole thing work :) Commented Apr 7, 2011 at 9:24
  • From your use-case, it's unclear what the returned object is for. Commented Apr 7, 2011 at 9:25

2 Answers 2

13

Sure. You would do it like this:

public List<T> GetAll<T>(List<T> list, Func<T, bool> where)
{
    return list.Where(where).ToList();
}

You would call it like this:

var result = GetAll(AllElements, o => o.ToString() == "lala");

You could even create it as an extension method:

public static List<T> GetAll<T>(this List<T> list, Func<T, bool> where)
{
    return list.Where(where).ToList();
}

and call it like this:

var result = AllElements.GetAll(o => o.ToString() == "lala");

But really, in your simple example, it doesn't make any sense, because it is exactly the same as using Where directly:

var result = AllElements.Where(o => o.ToString() == "lala").ToList();

However, if your GetAll method does some more stuff, it could make sense to pass the predicate to that method.

Sign up to request clarification or add additional context in comments.

2 Comments

Looks good, but I'd defer the actual execution of the query to the last possible moment by using IEnumerable<T> instead. It's a bad practice to take concrete containers as arguments.
I was just reusing his type. I agree, that he should use IEnumerable<T> instead.
1

You could pass some sort of predicate to the method:

var query = GetAll(x => x.ToString() == "lala");

// ...

public IEnumerable<object> GetAll(Func<object, bool> predicate)
{
    return AllElements.Where(predicate);
}

2 Comments

So should we use Func<T, bool> like daniel said or Func<object, bool>
Well, Daniel's version is more generic and flexible, but since AllElements is a List<object> then Func<object,bool> will suffice.

Your Answer

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.