Question

Which one of this syntax have better performance and speed in searching between data?

First alternative:

this.Message = pageContentsli
    .Where(m => m.PName == "Message")
    .First()
    .ContentValue;

Second alternative:

  foreach (PageContentsModel pc in pageContentsli)
  {
     if (pc.PName == "Message"){
        this.Message = pc.ContentValue;
        break;
      }
  }
Was it helpful?

Solution

Before continuing with the comparison, you should move the condition inside First like this:

this.Message = pageContentsli.First(m => m.PName == "Message").ContentValue;

As far as the performance goes, you should see no difference. On readability, however, the modified LINQ version wins hands down.

OTHER TIPS

First of all let me explain what both syntax actually does.

In the first syntax (where), it process the element one by one and if it catches m.PName="Message", it returns the requested value to this.Message and then the processing stops.

In the second syntax (foreach), it process the element one by one and when it catches m.PName="Message", it assigns the values to this.Message and again it starts processing for the rest of the element.

So eventhough the value is found, the second syntax doesn't stop and so it takes more time to complete than the first syntax.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top