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
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
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
Tôi không thấy phương thức 'OrderByDescending' cho' Dictionary'. – Kache