someone
someone

Reputation: 575

how can I convert this foreach loop to linq?

I'm very new to Linq. I want to convert these lines of code to linq lambda expression, If it makes sense how can I achieve?

foreach (var Type in Essay.Text)
{
     string text =
          $"{"here is result"}\n{method(Type)}";
     if (text.Length <= 20 && !string.IsNullOrEmpty(method(Type)))
     {
          Essay.Total += text;
     }
}

Upvotes: 0

Views: 86

Answers (3)

lsedlacek
lsedlacek

Reputation: 323

A few pointers:

  • There is no reason to call method twice, just cache it by using let
  • You can also check the length of the text before constructing the final string

This should do the job for you:

var texts = from type in essay.Text
            let methodResult = method(type)
            where !string.IsNullOrEmpty(methodResult)
            let text = $"here is result\n{methodResult}"
            where text.Length <= 20
            select text;

essay.Total += string.Concat(texts);

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39946

Something like this:

foreach (var type in from type in Essay.Text 
         let text = $"{"here is result"}\n{method(Type)}"
         where text.Length <= 20 && !string.IsNullOrEmpty(method(Type)) select type)
{
    Essay.Total += type;
}

Upvotes: 1

Backs
Backs

Reputation: 24903

With help of Resharper:

Essay.Total = string.Concat(
            Essay.Text.Select(Type => new {Type, text = $"{"here is result"}\n{method(Type)}"})
                .Where(@t => @t.text.Length <= 20 && !string.IsNullOrEmpty(method(@t.Type)))
                .Select(@t => @t.text)
            );

Upvotes: 2

Related Questions