简体   繁体   中英

How can i convert foreach loop to linq statements?

Thats my code.

foreach (var item in dtos)
{
      if (item.sample1 != SelectedDto.sample2)
      {
            adi.AppendLine(item.sample3.ToString() + " , " + item.sample1 + " , " + item.sample4);
      }

}

And thats my code which i try.

 if (dtos.Any(x => x.sample1 != SelectedDto.sample2)) ?????

Well, you can use linq to extract the informations that you need to add to the StringBuilder and then add them in this way

var selections = dtos.Where(x => x.sample1 != SelectedDto.sample2)
                     .Select(k => $"{k.sample3} , {k.sample1} , {k.sample4}");
adi.Append(string.Join(Environment.NewLine, selections));

Here we use the Where enumerable to extract all the dtos that match the condition and the use the sequence obtained to build a set of strings from the items extracted.

At this point we can add everything to the StringBuilder with a single line joining together the extracted strings.

As you can see, this is shorter code, but is it really necessary and an improvement versus the previous code?. I have not tested it with enough data to have strong confidence but I have a feeling that from a performace point of view the linq version is weaker than the normal for...loop.

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