简体   繁体   English

在C#中将包含if语句的foreach循环覆盖到linq方法语法中

[英]Coverting a foreach loop containing an if statement into linq method syntax in C#

I am trying to convert this to a linq statement with method syntax. 我正在尝试使用方法语法将此转换为linq语句。 I am not sure how to do it when teh foreach loop has an if statement. 我不确定在foreach循环中有if语句时该怎么做。 In the code below, MyMethodToConvert replaces the string "Tomorrow" to DateTime.Now 在下面的代码中,MyMethodToConvert将字符串“ Tomorrow”替换为DateTime.Now

foreach (var data in MyCollection)
        {
            if (data.DeliveryDate.Equals("Tomorrow"))
            {
                data.DeliveryDate = MyMethodToConvert(DeliveryDate);
            }
        }

I tried this, t didn't work 我试过了,没用

MyCollection = MyCollection.Select(a =>
                {
                    a.DeliveryDate.Equals("Tomorrow")
                        ? MyMethodToConvert(DeliveryDate)
                        : a.DeliveryDate)
                    ;
                    return a;
        }).ToList();

But it didn't work. 但这没有用。

Go only this far: 仅走这么远:

foreach (var data in MyCollection.Where(x => x.DeliveryDate.Equals("Tomorrow")))
{
    data.DeliveryDate = MyMethodToConvert(DeliveryDate);
}

If the compile-time type of x.DeliveryDate is string , prefer: 如果x.DeliveryDate编译时类型为string ,则首选:

foreach (var data in MyCollection.Where(x => x.DeliveryDate == "Tomorrow"))
{
    data.DeliveryDate = MyMethodToConvert(DeliveryDate);
}

You could use this: 您可以使用此:

MyCollection = MyCollection.Select(data =>
{
    if (data.DeliveryDate.Equals("Tomorrow"))
        data.DeliveryDate = MyMethodToConvert(DeliveryDate);
    return data;
}).ToList();

Or, if you don't want any Semicolons in your code (I'll assume that you have a class named Delivery with a constructor just for the DeliveryDate ): 或者,如果你不想在你的代码中的任何分号(我假设你有只是为了DeliveryDate构造一个名为交货类):

MyCollection = MyCollection.Select(data => data.DeliveryDate.Equals("Tomorrow")
    ? new Delivery(MyMethodToConvert(DeliveryDate))
    : data).ToList();

However, I wouldn't suggest to use Linq in here. 但是,我不建议在这里使用Linq。 The only little bit useful use of Linq would be what Jeppe Stig Nielsen suggested. Linq唯一有用的用途就是Jeppe Stig Nielsen提出的建议。

How about this: 这个怎么样:

MyCollection.Where(d => d.DeliveryDate.Equals("Tomorrow"))
            .ToList()
            .ForEach(d => d.DeliveryDate = MyMethodToConvert(DeliveryDate));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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