Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带OrderBy的稳定排序_C#_Linq - Fatal编程技术网

C# 带OrderBy的稳定排序

C# 带OrderBy的稳定排序,c#,linq,C#,Linq,这个问题与这里的其他问题类似,但没有一个能给出我想要的确切答案 我有一个列表,如下所示: List<KeyValuePair<string, List<string>>> lstValuesTemp = new List<KeyValuePair<string, List<string>>>(); lstValuesTemp.Add(...); 2个问题: 在函数中放置什么 我得到一个编译器错误: 错误CS0411:无法从

这个问题与这里的其他问题类似,但没有一个能给出我想要的确切答案

我有一个
列表
,如下所示:

List<KeyValuePair<string, List<string>>> lstValuesTemp = new List<KeyValuePair<string, List<string>>>();
lstValuesTemp.Add(...);
2个问题:

  • 在函数中放置什么
  • 我得到一个编译器错误:

    错误CS0411:无法从用法推断方法“System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable,System.Func)”的类型参数。尝试显式指定类型参数


  • 谢谢您的帮助。

    如果您想按钥匙订购,则lambda需要将钥匙从您的物品中拔出。因此,因为您的列表是
    KeyValuePair
    s,所以它应该是
    a=>a.Key


    如果您对按字符串(或其他类型)排序的实际含义感到困惑,您应该查看
    IComparable
    接口。这是由类型为
    T
    的类实现的,以提供一种方法来比较类型为
    T
    的对象,即一个元素在另一个元素之前、之后或具有相同的位置。如上所述,
    String
    实现了
    IComparable

    对于方法,您可以这样做

    var sortedArray = lstValuesTemp.OrderBy(a =>
    {
        return a.Key;
    });
    
    由于您只进行成员访问,因此还可以访问以下内容

    .OrderBy(a => a.Key);
    
    对于编译器错误,发生错误的原因很简单,因为您没有填写您的方法

    由于需要一个,它无法从使用情况推断TResult,因为您没有返回任何内容。如果您确实指定了类型参数,它会抱怨您的匿名方法没有返回值


    编辑:假设这不是非常抽象的,请参见您可以按如下键排序的类:

    var ordered = lstValuesTemp.OrderBy(v => v.Key);
    
    或者你可以用fonction点菜

    像这样声明函数:

    var sortedArray = lstValuesTemp.OrderBy(a =>
    {
           //What to put here?             
    });
    
    public static string CustomOrder(KeyValuePair<string, List<string>> item)
    {
        //TODO: add some logic that return a string to compare this item
    }
    

    你想按什么排序?您发现OrderBy的文档中有哪些方面令人困惑?在研究如何在其他常用资源中使用
    OrderBy
    时,您发现了关于该主题的哪些信息,以及在这些资源中哪些信息让您感到困惑?那么,您想按什么进行订购?钥匙?
    var ordered = lstValuesTemp.OrderBy(CustomOrder);