2014-02-05 34 views

回答

0

Min不返回item.It etc.If您想要的項目先拿到那麼最小值與where子句

var minValue = this.OrderItems.Min(p => p.OrderItemPrice); 
cOrderItem oItem = this.OrderItems.Where(p => p.CategoryID == catID 
              && p.n_IsOfferApplied == false 
              && p.OrderItemPrice == minValue) 
            .FirstOrDefault(); 
2

,你可以嘗試使用它返回一個整數或double結果爲了通過並獲取第一個元素

cOrderItem oItem = this.OrderItems. 
    Where(p => p.CategoryID == catID && p.n_IsOfferApplied == false). 
    OrderBy(p => p.OrderItemPrice).FirstOrDefault() 

這方面的工作圍繞我不wnat你使用,但比

var data = (from r in OrderItems 
      where r.CategoryID == catID && r.n_IsOfferApplied == false 
        group r by r.CategoryID into g 
        select new { id = g.Key, data= g.Min(a=>a.OrderItemPrice) }). 
       FirstOrDefault(); 

var cat = from r in OrderItems 
      join d in data data on d.id == r.CategoryID 
      select r; 

注意要爲了根據你的要求,你不:解決方案是不是我試過,不推薦使用

+3

從問題:*「我不想做訂貨」 * –

+1

@LB - 是的,我得到了,但林不知道爲什麼?因爲它的簡單方法做到這一點 –

+1

MinBy更容易,O(n)。 –

1

你必須針對在存在的最小值每個元素匹配集合。

cOrderItem oItem = this.OrderItems 
      .Where(p => 
         p.CategoryID == catID 
         && p.n_IsOfferApplied == false 

         //Read as: "where the OrderItemPrice value is equal to the lowest occuring value in this.OrderItems 
         && p.OrderItemPrice == this.OrderItems.Min(q => q.OrderItemPrice)) 

      .FirstOrDefault(); 

如果您需要多個項目(如果它們具有相同的OrderItemPrice),你可以做同樣的查詢,但在最後掉落.FirstorDefault()

+1

一個非常低效的方式。 –

-1

當您使用OrderBy時,它會在內存中創建源序列的新的有序副本(並再次枚舉源)。如果你想避免這種情況,你可以使用MoreLINQ MinBy(可從的NuGet)

cOrderItem oItem = OrderItems 
       .Where(p => p.CategoryID == catID && !p.n_IsOfferApplied) 
       .MinBy(p => p.OrderItemPrice); 

注意:它會拋出異常,如果沒有匹配的項目,所以你可以使用自己的擴展,如果它返回默認值可能不匹配會發現:

public static T MinBy<T, TKey>(
     this IEnumerable<T> source, Func<T, TKey> selector) 
    { 
     // throw if source or selector is null 
     using (var iterator = source.GetEnumerator()) 
     { 
      if (!iterator.MoveNext()) 
       return default(T); 

      var min = iterator.Current; 
      var minKey = selector(min); 
      IComparer<TKey> comparer = Comparer<TKey>.Default; 

      while (iterator.MoveNext()) 
      { 
       var current = iterator.Current; 
       var currentKey = selector(current); 
       if (comparer.Compare(currentKey, minKey) < 0) 
       { 
        min = current; 
        minKey = currentKey; 
       } 
      } 

      return min; 
     }    
    } 
+0

只是有趣的 - 這個解決方案有什麼問題?它不使用排序,它修復了默認MinBy實現中空序列的問題 –

相關問題