【问题标题】:How to use a LINQ in order to remove Min and Max value in List如何使用 LINQ 删除列表中的最小值和最大值
【发布时间】:2014-12-26 00:39:57
【问题描述】:

我有一个如下列表。

List<int> temp = new List<int> { 3, 5, 6, 8, 2, 1, 6};

我将使用 LINQ 删除上面列表中的最小值和最大值。

例如,下面的 sn-p 代码只是示例,不起作用。

var newValue = from pair in temp
               select pair < temp.Max() && pair > temp.Min()

希望结果如下所示;

newValue = {3, 5, 6, 2, 6 }

我试过谷歌搜索,但还没有找到合适的例子。

当我使用 LINQ 时它可以工作吗?感谢您的宝贵时间。

【问题讨论】:

  • 运行代码时会发生什么?
  • 不起作用。只是空。

标签: c# linq list


【解决方案1】:

您应该使用where

from pair in temp
where pair < temp.Max() && pair > temp.Min()
select pair

您当前的方法将选择值是否在范围内,而不是过滤它们。这就是where 子句的用途。

【讨论】:

    【解决方案2】:

    试试这个:-

    var query = temp.Where(x => x != temp.Min() && x != temp.Max()).ToList();
    

    工作Fiddle

    【讨论】:

    • 不错!请注意,如果有任何重复,它将删除所有最小值和最大值。
    【解决方案3】:

    如果您只需要删除最小值和最大值,为什么不直接使用 remove()?这对有什么需求?

        List<int> temp =new List<int>() { 3, 5, 6, 8, 2, 1, 6 };
        temp.Remove(temp.Max());
        temp.Remove(temp.Min());
    

    或者类似的东西,如果你需要保持临时并且宁愿在副本上工作

    temp.Sort();
    temp.Skip(1).Take(temp.Count - 2).ToList();
    

    【讨论】:

      【解决方案4】:

      你怎么能在通用集合中添加一个数组。您还必须将查询结果转换为列表。按照@Matthew Haugen 的建议使用where 子句。

      List<int> temp = new List<int>();// {3, 5, 6, 8, 2, 1, 6}
      
      temp.Add(3);
      temp.Add(5);
      temp.Add(6);
      temp.Add(8);
      temp.Add(2);
      temp.Add(1);
      temp.Add(6);
      
      List<int> newValue = (from n in temp 
                            where n > temp.Min() & n < temp.Max() 
                            Select n).ToList();
      

      【讨论】:

      • 看用途我觉得,不一定要转成list。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多