我使用的是以下C#代码:
//Custom structure
struct IndexedWord
{
public string Word;
public int Index;
}
static void Main(string[] args)
{
string[] wordsToTest = {"word1", "word2"};
var query = wordsToTest
.AsParallel()
.Select((word, index) =>
new IndexedWord {Word = word, Index = index});
foreach(var structs in query)
{
Console.WriteLine("{0},{1}", structs.Word,structs.Index);
}
Console.WriteLine();
Console.ReadKey();
}
//输出word1,0 word2,1
问:上面的代码运行良好。在执行代码时,“选择”查询操作符中的lamba表达式返回自定义结构"IndexedWord“的实例。表达式的参数从wordToTest[]数组接收参数值。例如,如果向参数"word“传递了值"word1",则向参数" index”传递了wordToTest[]数组中对应的索引位置"word1“。我不能准确地理解在查询的哪个点(可能在内部)提取参数并将参数传递给lambda表达式。如何提取wordsToTest[]数组的数据及其索引位置,并将其传递给lamba表达式的参数?是什么导致了这种提取?请澄清这一点。谢谢。
发布于 2016-09-21 00:37:47
你听说过c#中的并行编程吗?这是相同的,只是与查询。该查询与main方法并行执行。
发布于 2016-09-21 04:50:15
“选择”方法是从源数组wordsToTest[]中提取每个数据值及其相应索引值的方法。
函数调用:
wordsToTest.Select((word, index) =>
new IndexedWord { Word = word, Index = index });
调用构造函数:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, int, TResult> selector)
上面提到的Select()方法属于可枚举类。有关更多详细信息,请参阅下面提到的链接:https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx
谢谢。
https://stackoverflow.com/questions/39605719
复制相似问题