2013-11-25 78 views
0

我有一個集合,我需要找到一個價格最低的物品,如果超過1個,默認情況下應該選擇任何物品,並且isPriceSelected屬性需要設置爲false。如何使用linq在集合中查找最小值?

我正在嘗試這樣的事情。

lstBtn.Where(p => p.CategoryID == btnObj.CategoryID && 
        p.IsSelected == true && p.IsPriceApplied == true) 
     .ToList() 
     .Min(m=>m.Price) 
+0

爲什麼要使用Linq?只需簡單地這樣做:myList.Sort();然後選擇列表中的第一個元素 – Tinwor

+0

@Tinwor:因爲他的要求是獲得最低價格,而不是對原始集合進行排序。除此之外,'lstBtn.Sort'不會自動按「Price」排序。 –

回答

7

只需選擇您希望從最小的財產:

var minimumPrice = lstBtn 
    .Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected && p.IsPriceApplied) 
    .Min(p => p.Price); 

如果你真的想找到你需要訂購的收集價格最低的項目:

var itemWithMinimumPrice = lstBtn 
    .OrderBy(p => p.Price) 
    .FirstOrDefault(p => p.CategoryID == btnObj.CategoryID && p.IsSelected && p.IsPriceApplied); 

或這個,可以更高效:

var itemWithMinimumPrice = lstBtn 
    .Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected && p.IsPriceApplied) 
    .OrderBy(p => p.Price) 
    .FirstOrDefault(); 

Enumerable.FirstOrDefault返回一個項目或null如果沒有項目與謂詞匹配。

+0

好奇心想知道,這也可以是'lstBtn.Min(p => p.CategoryID == btnObj.CategoryID && p.IsSelected && p.IsPriceApplied);'? –

+0

@MichaelPerrenoud:如果至少有一個項目與此謂詞不匹配,則返回'false',否則返回true(因爲true比false更高)。但顯然不是OP要的 –

+0

好,所以如果我想要像這樣內聯條件,我必須返回實際值;實際上並沒有獲得什麼真正的東西,因爲它更具可讀性,並且與Where'一樣高效,對吧? –

2

你可以嘗試這樣的事情:

var result = lstBtn 
    .Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected && p.IsPriceApplied) 
    .OrderBy(p => p.Price) 
    .First(); 

這將首先找到已指定CategoryIDIsSelected所有項目,並IsPriceApplied都設置爲true,然後通過Price項目進行排序,並返回的第一個項目以最低的價格。

+0

如何在同一個語句中將isPriceApplied設置爲false。 – NoviceToDotNet

+1

最好的選擇是在第二個語句'result.IsPriceApplied = false' –

1

開箱即用,linq只能用Min和Max方法返回實際值。 您可以使用一個好項目morelinq https://code.google.com/p/morelinq/wiki/OperatorsOverview 它有你需要的方法。對於我自己,我覺得這個項目有太多的方法,所以我只是從源頭上剪切和粘貼。 隨着morelinq你的代碼應該是這樣的:

lstBtn.Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected == true && p.IsPriceApplied==true).MinBy(m=>m.Price) 

另一種方法,如果您還需要獲得所有重複:

var lowestPriceProducts = lstBtn.Where(p => p.CategoryID == btnObj.CategoryID) 
    .GroupBy(p => p.Price, new { p.Price, Product = p}) 
    .OrderByDescending(x => x.Price) 
    .First() 
    .Select(x => x.Product) 
    .ToList() 

此查詢將返回一個列表(只有一個項目,如果有沒有重複的價格)的產品以最低的價格。那麼你可以用它做任何事情。

相關問題