2010-06-17 5 views
35

Tôi đã sau answer to another question, và tôi đã nhận:Chuyển đổi một IOrderedEnumerable <KeyValuePair <string, int>> thành một điển <string, int>

// itemCounter is a Dictionary<string, int>, and I only want to keep 
// key/value pairs with the top maxAllowed values 
if (itemCounter.Count > maxAllowed) { 
    IEnumerable<KeyValuePair<string, int>> sortedDict = 
     from entry in itemCounter orderby entry.Value descending select entry; 
    sortedDict = sortedDict.Take(maxAllowed); 
    itemCounter = sortedDict.ToDictionary<string, int>(/* what do I do here? */); 
} 

Visual Studio của yêu cầu cho một tham số Func<string, int> keySelector. Tôi cố gắng sau một vài ví dụ về bán có liên quan tôi đã tìm thấy trực tuyến và đưa vào k => k.Key, nhưng đó đưa ra một lỗi biên dịch:

'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' has some invalid arguments

Trả lời

47

Bạn đang định lập luận chung chung không chính xác. Bạn đang nói rằng TSource là chuỗi, khi trong thực tế nó là một KeyValuePair.

Cái này là chính xác:

sortedDict.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value); 

với phiên bản ngắn hạnh phúc:

sortedDict.ToDictionary(pair => pair.Key, pair => pair.Value); 
+0

Cảm ơn bạn rất nhiều vì đã xây dựng! Vì vậy, trong C#, 'pair => pair.Key' có kiểu' Func'? Làm thế nào để bạn khai báo một trong số đó? (Vì vậy, một trong những có thể làm 'sortDict.ToDictionary (funcKey, funcVal);'?) – Kache

+3

Thực ra, tôi đề nghị bạn không sử dụng cú pháp C# LINQ vì nó loại ẩn từ bạn những gì phương pháp bạn thực sự gọi, và ngoại hình cho C# ngôn ngữ. Tôi không bao giờ sử dụng nó bởi vì tôi nghĩ rằng nó xấu xí. Mẫu của bạn có thể được viết bằng C# không có linq như sau: 'sortedDict = itemCounter.OrderByDescending (entry => entry.Value)'. Không còn nữa, phải không? – Rotsor

+2

Tôi không thấy phương thức 'OrderByDescending' cho' Dictionary'. – Kache

8

Tôi tin rằng cách sạch làm cả hai cùng nhau: sắp xếp các từ điển và chuyển đổi nó trở lại một cuốn từ điển sẽ là :

itemCounter = itemCounter.OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value); 
0

Câu hỏi quá cũ nhưng vẫn muốn trả lời tham chiếu:

itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);