Running a simple LINQ query in parallel

后端 未结 2 1394
独厮守ぢ
独厮守ぢ 2021-01-03 23:13

I\'m still very new to LINQ and PLINQ. I generally just use loops and List.BinarySearch in a lot of cases, but I\'m trying to get out of that mindset where I ca

2条回答
  •  迷失自我
    2021-01-03 23:21

    For your first question, you should just replace Select with Where :

    var matchedStaff = allStaff.AsParallel().Where(s => s.Matches(searchString));
    

    Select is a projection operator, not a filtering one, that's why you are getting an IEnumerable corresponding to the projection of all your Staff objects from the input sequence to bools returned by your Matches method call.

    I understand it can be counter intuitive for you not to use select at all as it seems you are more familiar with the "query syntax" where select keyword is mandatory which is not the case using the "lambda syntax" (or "fluent syntax" ... whatever the naming), but that's how it is ;)

    Projections operators, such a Select, are taking as input an element from the sequence and transform/projects this element somehow to another type of element (here projecting to bool type). Whereas filtering operators, such as Where, are taking as input an element from the sequence and either output the element as such in the output sequence or are not outputing the element at all, based on a predicate.

    As for your second question, AsEnumerable returns an IEnumerable as it's name indicates ;) If you want to get a List you should rather call ToList() (as it's name indicates ;)) :

    return allStaff.AsParallel().Select(/* something */).ToList();
    

    Hope this helps.

提交回复
热议问题