Saeed Afshari
Saeed Afshari

Reputation: 949

How to cast instance of Enumerable<T>.Where(Predicate) to IEnumerable<T>?

I'm writting a c# code generator. In some place I must cast return type of Linq's method like WhereSelectListIterator to IEnumerable type. How can I do it?

Scenario: I have an instance of a List named aList. I write following expression in a Textbox:

aList.Where(item => item.StartsWith("s")).Select(item => item.ToUpper()).ToList().Count

I need to write an application to evaluate my expression. I know that i must write an C# code generator to evaluate my expression. If I evaluate above expression directly it is works. But suppose that I have following scenario :

public Interface IInterface
{
}
public class MyClass:IInterface
{
    public int Id = 10;
    public IInterface GetInstance()
    {
        return new MyClass();
    }
}

public class Program
{
    public static void Main()
    {
        var myClass = new MyClass();
        myClass.GetInstance().Id.ToString();
    }
}

When I use Id property after calling GetInstance() method it cause to CLR raise an exception because IInterface hasn't Id property. I need to cast return type of GetInstance() to MyClass first then use Id property. How can I do this cast dynamically. One solution is using dynamic object.

var myClass = new MyClass();
dynamic x = myClass.GetInstance();
dynamic y = myClass.Id;
y.ToString();

But dynamic object has problem with Extension methods(ex : Where(), Take() , ...). What can I do?

Upvotes: 2

Views: 3749

Answers (2)

RePierre
RePierre

Reputation: 9566

You can call extension methods on dynamic objects like this:

dynamic result = Enumerable.Where(collection, (Func<dynamic, bool>)delegate(dynamic item)
                                              {
                                                   return item.Id == id;
                                               });

Upvotes: 1

David Yaw
David Yaw

Reputation: 27864

In answer to the question you ask in the title, The result of Enumerable<T>.Where(Predicate) implements IEnumerable<T>, just cast it, no need to do anything fancy. See here: Enumerable..Where(TSource) Method (IEnumerable(TSource), Func(TSource, Boolean))

As for the rest, why are you trying to generate C# code? If you're trying to evaluate a code snippet that was entered at runtime, why not use the C# compiler to compile it? I Googled for "C# programmatic compilation", and the first result was this Microsoft support page: How to programmatically compile code using C# compiler

Upvotes: 1

Related Questions