Reputation: 29
I am new to C# linq. Just wondering if it is possible to combine the following two linq statements into one.
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.
Upvotes: 2
Views: 191
Reputation: 39277
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
.
If however you want to capture the line structure somehow in what you are processing, e.g. to create a sequence of sequences representing the lines and the words on each line then use Select
again.
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>>
.
Upvotes: 0
Reputation: 6882
SelectMany is your friend:
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" });
Upvotes: 3