Skip to main content
 首页 » 编程设计

c#之特定的 plinq 查询

2024年02月23日14freeliver54

我想选择一个在 C# 中具有最大值的 ID dictionary<int, double>

例如

初始字典

 1   0.8    
 2   0.78    
 3   0.9    
 4   0.87    

选择后

 3   0.9    

我当前的代码

dic.AsParallel().Max(x => x.Value); 

请您参考如下方法:

听起来您想要一个 MaxBy 结构。这在正常的 LINQ to Objects 中不存在,尽管我在 MoreLINQ 中有一个,所以你会写:

var result = dictionary.MaxBy(pair => pair.Value); 

但是,这不会以您想要的方式并行化。你至少可以尝试使用this overload of ParallelEnumerable.Max创建了您自己的包含相关值的可比类型:

public class ComparablePair : IComparable<ComparablePair> 
{ 
    // Have key and value, then implement IComparable<T> by 
    // comparing values 
} 

然后使用:

var result = dictionary.AsParallel() 
                       .Max(pair => new ComparablePair(pair));