簡體   English   中英

如何使用LINQ來刪除List中的Min和Max值

[英]How to use a LINQ in order to remove Min and Max value in List

我有一個如下所示的列表。

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

我將使用LINQ刪除Above List中的Min和Max值。

例如,下面的代碼段只是示例,不起作用。

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

希望,我希望結果如下;

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

我試過谷歌搜索,但還沒找到合適的例子。

當我使用LINQ時它可以工作嗎? 謝謝你的時間。

你應該在where使用。

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

您當前的方法將選擇值是否在范圍內,而不是過濾它們。 這就是where子句的用途。

嘗試這個:-

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

工作小提琴

如果你只需要刪除最小值和最大值,為什么不只是使用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();

你怎么能在Generic Collection中添加一個數組。 您還必須將查詢結果轉換為列表。 使用@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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM