2014-05-22 56 views
0

我有一個列表,我使用的是團隊的總銷售額。如何使用LINQ從列表中獲取索引

lstTeamSales.OrderBy(x => x.TotalSales); 

該列表的int userIDdecimal totalSales。我可以訂購totalSales。我怎麼能在那一點上找出登錄人員的等級?

我知道我可以將通過其userID登錄的人與列表中的userID進行比較。如果他是排名第3的銷售我需要回到他的等級的一個int這將是排名3.

+2

我不完全理解你的問題的標題......你在僞裝什麼? –

+0

:D我想他想寫「Take」而不是「Fake」 –

+0

標題已更新。 –

回答

2

的問題可以被改述爲「我如何在IEnumerable的元素的索引」。下面是答案:How to get index using LINQ? 這裏是如何使用它:

int rank = lstTeamSales.OrderBy(x => x.TotalSales).FindIndex(x => x.userID == currentUserID); 

,這將是略多於Select基礎的方法更有效。

更新

這似乎不支持LINQ .FindIndex。任何想法如何實現該功能?

我可能已經想通了它現在測試它。我剛剛在ORderBy()之後添加了.ToList()。

不 - 不 - 不!它殺死了整個想法:(這個想法是添加extension methodFindIndex IEnumerable。然後使用它。見例如:

static class FindIndexEnumerableExtension 
{ 
    public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) 
    { 
     if (items == null) throw new ArgumentNullException("items"); 
     if (predicate == null) throw new ArgumentNullException("predicate"); 

     int retVal = 0; 
     foreach (var item in items) 
     { 
      if (predicate(item)) return retVal; 
      retVal++; 
     } 
     return -1; 
    } 
} 

class YourClass 
{ 
    void YourMethod() 
    { 
     lstTeamSales.OrderBy(x => x.TotalSales).FindIndex(x => x.UserID == currentUserID); 
    } 
} 

在定義FindIndexEnumerableExtensionFindIndex擴展方法,你可以在你的代碼的任何地方使用此方法。所有你需要的只是添加using指令與模塊,其中FindIndexEnumerableExtension被定義。基本上,這是LINQ的工作原理。

如果您不想使用此解決方案,那麼至少應將lstTeamSales轉換爲List,然後再對其進行排序。並使用List<>.Sort()方法進行分類。

+0

謝謝!是的,那正是我想要的。 –

+0

歡迎您:) –

+0

它出現.FindIndex不支持LINQ。任何想法如何實現該功能? –

1

您可以使用select extenstion,需要一個Func<TSource, Int32, TResult>(或等同的表達),像這樣:

var userId = /* the userId */; 
lstTeamSales.OrderBy(x => x.TotalSales).Select((x, i) => new 
{ 
    x.UserId, 
    x.TotalSales, 
    Rank = i + 1 
}).FirstOrDefault(x => x.UserId == theUserId); 

這將返回一個對象,其中包含用戶標識,總銷售額以及用戶標識所固定的級別。如果在集合中沒有實體UserId = theUserId,它將返回null

索引(示例中的i)基於0。根據需要調整。

1

鑑於銷售總額,lstTeamSales並表示你希望找到,userSales軍銜的銷售數字的列表,你會需要的是總銷售額的lstTeamSales超過userSales數量。如果它是你想要的排名,那麼你可能想要排除排名中的關係(即如果前兩名銷售數字都是1000,那麼他們都將排名1)

你可以簡單地通過預測只有Select的銷售數字,除去領帶與Distinct呼叫,然後使用Count

lstTeamSales.Select(x => x.TotalSales).Distinct().Count(x => x > userSales) 

這將使你的銷售是比當前用戶較高的總數。從那裏,當前用戶的排名是一個高於號碼:

var rank = 1 + lstTeamSales.Select(x => x.TotalSales).Distinct().Count(x => x > userSales) 
0

Select((item, index) => ...)表格允許這樣(如Simon所示),但由於DMac提到您可能要考慮重複。要在Select納入本,你可以使用GroupBy

lstTeamSales 
    .OrderByDescending(x => x.TotalSales).GroupBy(x => x.TotalSales) 
    .Select((group, i) => new { 
     Rank = i + 1, 
     Users = group.Select(x => x.UserId) 
    }) 

這會爲您提供行列的有誰有秩用戶的列表一起列表。或者你可以用SelectMany扁平化這一點,得到其排名每個用戶:

lstTeamSales 
    .OrderByDescending(x => x.TotalSales).GroupBy(x => x.TotalSales) 
    .SelectMany((x, i) => new { 
     Rank = i + 1, 
     User = x.UserId 
    }) 

您可以過濾這個序列找到用戶,但如果你只想要查找特定用戶的級別,然後DMAC的解決方案是最直接的。例如,如果您想列出前5名賣家(參見Take),以上就會更有用。