简体   繁体   中英

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..
}

Try to get you your desired value by Where() and get it through FirstOrDefault() method:

var o = a.list.Where(o => o.Status == Good)).FirstOrDefault();
if (o != null) {
    OtherMethod(a, o, b)
}

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.

assuming here you want to pass "o" as parameter in "OtherMethod()" for this you can create a new List as

 List<string> c = new List<string>();

and then add value of o to List c according to logic.

    c.Add()
//pass c as parameter to method
    OtherMethod(a, c, b);

hope it helps

This would be also worth a shot, which checks all the objects, and executes them accordingly

u.Orders.Where(o => o.Status == EnumsDTO.OrderStatus.NotPaid)
        .Select(o => OtherMethod(a, o, b));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM