【问题标题】:How to get maximum and minimum values using Lambda function over a list of key and value in C#?如何在 C# 中的键和值列表上使用 Lambda 函数获取最大值和最小值?
【发布时间】:2021-12-23 07:32:51
【问题描述】:

我有一个清单。 KeyValue 有 2 个参数。字符串键和十进制值。

public class KeyValue
{
    public string Key {get; set;}
    public decimal Value {get; set;}
}
data = data.Select(a => new KeyValue
       {
            Key = (string.Concat(a.Key.Select(e => Char.IsUpper(e) ? " " + e : e.ToString())).TrimStart(' ')),
            Value = a.Value
       }).ToList();

这是填写“数据”列表中的键、值。 如何填写此列表中的值 [1st max.值,第一个最小值,第二个最大值,第二个最小值.....]

【问题讨论】:

  • 嗨 Shishank,欢迎来到 StackOverflow。基本上你的问题是如何创建具有给定模式的新列表。那是对的吗?如果是,那么您是否尝试过任何方法?你能告诉我们你的尝试吗?如果您遇到任何错误,您可以将其添加到问题中吗?如果您提供相同的Minimal reproducible example,那就太好了

标签: c# lambda


【解决方案1】:

.ToList(); 替换为

.GroupBy(x => x.Key, x => x.Value, (k, g) => new { Key = k, Max = g.Max(), Min = g.Min() } ).ToList();

这使用了 GroupBy 的重载,即:

GroupBy(
  property_from_enumerable_to_group_on,  //group by key
  property_from_enumerable_to_output,    //just emit values
  function_to_apply_to_output.           //g is a list of Value so it does min and max on them
)

data.GroupBy(x => x.Key, x => x.Value, (k, g) => new { Key = k, Max = g.Max(), Min = g.Min()).ToList();

如果您想要一点性能提升,您甚至可以用它替换您的 Select;您的逻辑似乎将 PascalCase 字符串更改为 Pascal 空间字符串,但在分组之前不必对一百万个字符串执行此操作,它可以在组中出现的 10 个字符串上完成。此外,如果我们使用 select 的重载允许我们检测 char 的索引,我们可以避免对第一个 char 进行替换,这意味着我们可以避免 Trim,所以也许像

data.GroupBy(
  x => x.Key, 
  x => x.Value,
  (k, g) => new {
    Key = string.Concat(a.Key.Select((e, x)=> x > 0 && Char.IsUpper(e) ? " "+ e : e.ToString())),
    Max = g.Max(),
    Min = g.Min()
 }).ToList();

如果您决定取消透视,您可以将 minmax 放入您 SelectMany 的数组中:

data.GroupBy(
  x => x.Key, 
  x => x.Value,
  (k, g) => new {
    Key = string.Concat(a.Key.Select((e, x)=> x > 0 && Char.IsUpper(e) ? " "+ e : e.ToString())),
    Vals = new [] { g.Min(), g.Max() }
 }).SelectMany(g => g.Vals, (g, m) => new KeyValue { Key = g.Key, Value = m} )
 .ToList();

【讨论】:

  • "{" 在 "new" @Caius Jard 之后没有关闭使用
  • 刚刚也抓到了,谢谢你告诉我?
  • 在最后一个解决方案中,我得到的 'a' 在当前上下文中不存在 @Caius Jard
  • 无法在此范围内声明局部参数 x,因为该名称在封闭的局部范围中用于定义局部参数 @Caius Jard
  • 第一个解决方案是给出错误:“无法将类型 Systems.Generic.List 隐式转换为 List @CaiusJard
【解决方案2】:

这个问题可以分两步解决。

  1. 使用 linq 查询根据值对列表进行排序。
  2. 使用此方法:https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/ 我填写了列表中的最大最小值。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2020-09-22
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 2021-04-14
  • 2018-10-30
  • 1970-01-01
相关资源
最近更新 更多