如何将这个foreach循环转换为linq
本文关键字:循环 转换 linq foreach | 更新日期: 2023-09-27 18:19:24
我对Linq很陌生。我想将这些代码行转换为linq lambda表达式,如果有意义,我该如何实现?
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;
}
}
使用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)
);
像这样:
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;
}
几个指针:
- 没有理由调用方法两次,只需使用let缓存它
- 您还可以在构造最终字符串之前检查文本的长度
这个应该可以帮你完成这项工作:
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);