Question

public class EcImageWrapper
{

    //etc...

    public IQueryable<EcFieldWrapper> ListOfFields
    {
        get
        {
            //logic here

            return this.listOfFields.AsQueryable();
        }
    }

    public EcFieldWrapper FindBy(Expression<Func<EcFieldWrapper, int, bool>> predicate)
    {
        return this.ListOfFields.Where(predicate).SingleOrDefault();
    }

    public EcFieldWrapper FindByName(string fieldName)
    {
        return this.FindBy(x => x.Name.ToUpper() == fieldName.ToUpper());
        //error here, wanting 3 arguments
        //which makes sense as the above Expression has 3
        //but i don't know how to get around this
    }

For some reason the Expression> Is requiring me to use 3 arguments, in the past I've only used 2 for the instance in question. However, now I'm wanting to do a find by on a collection within this instance.

I'm getting the following errors:

Delegate 'System.Func<MSDORCaptureUE.Wrappers.EcFieldWrapper,int,bool>' does not take 1 arguments
The best overloaded method match for 'CaptureUE.Wrappers.EcImageWrapper.FindBy(System.Linq.Expressions.Expression<System.Func<CaptureUE.Wrappers.EcFieldWrapper,int,bool>>)' has some invalid arguments
Argument 1: cannot convert from 'string' to 'System.Linq.Expressions.Expression<System.Func<CaptureUE.Wrappers.EcFieldWrapper,int,bool>>'

Desired outcome: To be able to use a predicate of the return type EcFieldWrapper and predicate type of EcFieldWrapper within the instance of a class EcImageWrapper

Why does it require 3? Why the int?

Was it helpful?

Solution

The existing method doesn't require 3 arguments - it requires an Expression<Func<EcFieldWrapper, int, bool>> because that's what you've declared your method to accept. That would be something like:

// This version ignores the index, but you could use it if you wanted to.
(value, index) => value.Name.ToUpper() == fieldName.ToUpper()

The index would be the position within the collection, as you're calling this overload of Queryable.Where.

Assuming you don't want the index, I strongly suspect you just want to change your FindBy method to:

public EcFieldWrapper FindBy(Expression<Func<EcFieldWrapper, bool>> predicate)
{
    return this.ListOfFields.Where(predicate).SingleOrDefault();
}

Or more simply, using the overload of SingleOrDefault which accepts a predicate:

public EcFieldWrapper FindBy(Expression<Func<EcFieldWrapper, bool>> predicate)
{
    return this.ListOfFields.SingleOrDefault(predicate);
}

That should work fine - and if it doesn't, you should tell us what happens when you try it.

OTHER TIPS

No need for Find method. Do everything in FindByName.

public EcFieldWrapper FindByName(string fieldName)
{
    fieldName = fieldName.ToUpper();
    return ListOfFields
       .SingleOrDefeault(x => x.Name.ToUpper() == fieldName);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top