簡體   English   中英

LINQ問題......需要獲得具有最小值的元素

[英]LINQ question … need to get element with min value

我是linq的新手,所以我還在努力....

我有一組控件(每個控件都有一個Point類型的位置)。 我需要從集合中刪除具有最低Y值(頂部控件)的控件。

一個例子將非常感謝!

像這樣的東西:

collection.Remove(collection.OrderBy(c => c.Location.Y).First());

訂購非常昂貴,因此根據您的使用情況,您還可以找到價值最低的商品,然后將其刪除:

collection.Remove(collection.First(c => c.Y == collection.Min(c2 => c2.Y)));

這列出最多三次列表,通常這應該比OrderBy快,但如果性能對您很重要,那么先測量。

您只需要找到該項並將其刪除即可。 刪除非常清楚,但在查找時,您可以使用這樣的Aggregate方法:

collection
   .Remove(collection
       .Aggregate((c1, c2) => c1.Point.Y < c2.Point.Y ? c1 : c2)
   )
);

訂購更貴。 只需獲得最小值。

var lowest = (from c in collection
              where c.X == collection.Min(i => i.X)
              select c).FirstOrDefault();
collection.Remove(c);

請記住, LINQ代表語言INtegreated 查詢 也就是說,它意味着用作查詢工具,而不是用於修改集合。

也就是說,您可以使用LINQ找到需要刪除的控件。 然后按正常方式刪除它。

// Let's say controls is a ControlCollection
var enumerable = controls.Cast<Control>();
int minimumY = enumerable.Min(c => c.Location.Y);
Control topControl = enumerable.Where(c => c.Location.Y == minimumY);

controls.Remove(topControl);

下面是一個擴展方法,允許您選擇min元素而不是min值。 你可以像這樣使用:

var lowest = collection.MinElement(x => xY);

然后你可以用collection.Remove(lowest)刪除元素。

public static T MinElement<T>(this IEnumerable<T> source, Func<T, int> selector) {
    if (source == null) {
        throw new ArgumentNullException(nameof(source));
    }

    int minValue = 0;
    T minElement = default(T);
    bool hasValue = false;

    foreach (T s in source) {
        int x = selector(s);
        if (hasValue) {
            if (x < minValue) {
                minValue = x;
                minElement = s;
            }
        } else {
            minValue = x;
            minElement = s;
            hasValue = true;
        }
    }

    if (hasValue) {
        return minElement;
    }

    throw new InvalidOperationException("MinElement: No elements in sequence.");
}
collection.Remove( collection.Min( c => c.Y ));

暫無
暫無

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

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