简体   繁体   English

C#Linq语句

[英]C# linq statements

I am new to C# linq. 我是C#linq的新手。 Just wondering if it is possible to combine the following two linq statements into one. 只是想知道是否有可能将以下两个linq语句合并为一个。

var l = str.Split(new[] { '\n' },   
        StringSplitOptions.RemoveEmptyEntries)
        .Select(p => p.Trim())
        .Where(p =>!string.IsNullOrWhiteSpace(p))
        .ToArray();
foreach (var w in l)    {    
     var dd = w.Split(new[] { ' ' },   
     StringSplitOptions.RemoveEmptyEntries)
     .Select(p => p.Trim())
     .Where(p => !string.IsNullOrWhiteSpace(p))
     .Concat(new[] { "\n" });
    }

Any help is appreciated. 任何帮助表示赞赏。 Thanks a lot. 非常感谢。

SelectMany is your friend: SelectMany是您的朋友:

  var l = str.Split(new[] { '\n' },   
    StringSplitOptions.RemoveEmptyEntries)
    .Select(p => p.Trim())
    .Where(p =>!string.IsNullOrWhiteSpace(p))
    .SelectMany(w => w.Split(new[] { ' ' },  ringSplitOptions.RemoveEmptyEntries)
    .Select(p => p.Trim())
    .Where(p => !string.IsNullOrWhiteSpace(p))
    .Concat(new[] { "\n" });

If all you care about is a bag of words, use string.Split and pass it both the newline character and the space character, there is no need to do this in two steps and to combine them using SelectMany . 如果您只关心string.Split单词,请使用string.Split并将换行符和空格符传递给它,无需分两步进行操作,也无需使用SelectMany进行组合。

If however you want to capture the line structure somehow in what you are processing, eg to create a sequence of sequences representing the lines and the words on each line then use Select again. 但是,如果您想以某种方式捕获正在处理的行结构,例如创建代表行和每行单词的序列序列,请再次使用“ Select

var l = str.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(p => p.Trim())
    .Where(p =>!string.IsNullOrWhiteSpace(p))
    .Select(l => l.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
      .Select(p => p.Trim())
      .Where(p => !string.IsNullOrWhiteSpace(p)));

l is IEnumerable<IEnumerable<string>> . l是IEnumerable<IEnumerable<string>>

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

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