LINQ expression to extract only two word phrases
I have a list (of objects), with one property in the object as a string.
This property always contains single words and would like to loop through all sequential combinations in pairs, for example:
I am trying to write LINQ which will allow me to iterate through the data in the following format:
Could anybody suggest the most efficient way of doing this.
I have a bunch of conditional IF statements at the moment that I'm looking to remove.
I think you want:
var pairs = words.Zip(words.Skip(1), (x, y) => x + " " + y);
That's assuming you're using .NET 4, which is when Zip
was introduced.
You could write your own extension method:
public static IEnumerable<Tuple<TOutput, TOutput>> Pairwise<TInput, TOutput>(this IEnumerable<TInput> collection, Func<TInput, TOutput> func)
{
using (var enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext()) yield break;
TOutput first = func(enumerator.Current);
while (enumerator.MoveNext())
{
TOutput second = func(enumerator.Current);
yield return Tuple.Create(first, second);
first = second;
}
}
}
Which would be useable like so:
IEnumerable<string> pairs = yourCollection.Pairwise(element => element.Property).Select(t => t.Item1 + ' ' + t.Item2);
链接地址: http://www.djcxy.com/p/51384.html
上一篇: 需要C#Regex来替换字符串中的空格
下一篇: LINQ表达式仅提取两个单词短语