Search code examples
c#linqif-statementreturn

How do i return a value from LINQ into a parameter? C#


So there's this method:

public void Method(A a, B b)
{
     OtherMethod(a, a.list.ForEach(o => {if(o.Status == Good){ return o};), b)
}

OtherMethod() needs 3 params. I want that o to put in the parameters, but I don't know how. Anybody knows how?

The actual code:

public void AddProduct(UserDTO u, ProductDTO p)
{
    if(CheckForCurrentOrder(u) != 0) //returns ID of order with status = "NotPaid"
    {
        CreateEmptyOrder(u);
        SetProductInOrder(u, u.Orders.ForEach(o => { if (o.Status == EnumsDTO.OrderStatus.NotPaid) { return o}; }), p);
    }

//rest of database code thats not relevant..
}

Solution

  • You can use Linq's First() (or similar) method:

    OtherMethod(a, a.list.First(o => o.Status == Good), b)
    

    First will find the first item in a.list which matches the condition o.Status == Good (and will throw an exception is no items match this condition). You might want to use FirstOrDefault instead, which returns a default value if no items match this condition, of Single which ensures that only a single item matches this condition.