简体   繁体   English

LINQ按值对字典排序

[英]LINQ sort dictionary by value

I am trying to sort values Descending before pushing them into dictionary. 我正在尝试将降序的值推入字典之前进行排序。 The query works fine but i just need to add sorting functionality. 该查询工作正常,但我只需要添加排序功能。

Following is my original LINQ query 以下是我的原始LINQ查询

        List<Model> list = query1.Where(x => x.ItemsPrice.Any())
            .GroupBy(x => new { Student = query2.FirstOrDefault(y => y.Id == x. Id).Student.Name })
            .Select(x => new Model
            {
                StudentName = x.Key.Student,
                ClassItems = x.SelectMany(y => y. ItemsPrice)
                              .GroupBy(y => y. Price.item.Name)
                              .ToDictionary(y => y.Key, y => y.Sum(z => z.TotalPrice()))
            }).ToList();

I am trying the following code but it is giving this error 我正在尝试以下代码,但出现此错误

can not implicitly convert IOrderedEnumerables to System.Collection.Generic.Dictioanry. 无法将IOrderedEnumerables隐式转换为System.Collection.Generic.Dictioanry。

.ToDictionary(y => y.Key, y => y.Sum(z => z.TotalPrice())).OrderByDescending(y => y.Value)

Something like this should work for you: 这样的事情应该为您工作:

public class MyComparer : IComparer<int>
{
  public int Compare(int x, int y)
  {
    return x.CompareTo(y);
  }
}

// ...
private void DoStuff()
{
  var dict = new Dictionary<int, int> {{3, 300}, {2, 200}};
  var sortedDict = new SortedDictionary<int, int>(dict, new MyComparer());
}

Or in your specific scenario: 或在您的特定情况下:

private class DescendingComparer : IComparer<string>
{
  int IComparer<string>.Compare(string a, string b)
  {              
    return StringComparer.InvariantCulture.Compare(b, a);
  }
}

// ....
ClassItems = new SortedDictionary<string, float>(x.SelectMany(y => y. ItemsPrice)
                                                .GroupBy(y => y. Price.item.Name)
                                                .ToDictionary(y => y.Key, y => y.Sum(z => z.TotalPrice())),
                                               new DescendingComparer());

Note: adjust the key and value type of the sorted dictionary as well as the comparer type according to your needs! 注意:根据需要调整排序字典的键和值类型以及比较器类型!

The order that items are stored in a dictionary is not guaranteed. 不能保证项目在字典中的存储顺序。 Don't rely on it. 不要依赖它 When you retrieve items from the dictionary, you can sort it at that point. 当您从字典中检索项目时,您可以在那时对其进行排序。

"For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined." “出于枚举目的,字典中的每个项目都被视为代表值及其键的KeyValuePair结构。返回这些项目的顺序是不确定的。”

-- MSDN -MSDN

As Markus pointed out, if you really need order in your dictionary, use the OrderedDictionary<,> class or the SortedDictionary<,> class . 正如Markus指出的那样,如果您确实需要字典中的顺序,请使用OrderedDictionary<,>SortedDictionary<,>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM