为什么-9被认为大于1?

时间:2015-01-20 21:05:52

标签: c# linq

我拥有的数据集是:

Name                        Order        ID 
Summary                     1            147
Software Functionality     -9            211

我有这个LINQ查询:

string value = projectA.OrderByDescending(a => a.Order)
                       .ThenBy(a => a.Name)
                       .ToList()
                       .First()
                       .ID
                       .ToString();

我得到的答案是211,但我认为答案应该是147.为什么会这样?

注意:Order字段的类型为string

3 个答案:

答案 0 :(得分:3)

由于Orderstring,您获得了输出。作为证明,此示例将显示当它是一个整数时,您将获得正确的输出:

void Main()
{
    var list = new List<Project>() { new Project() { Order = 1, Id = 147, Name = "Summary" }, new Project() { Order = -9, Id = 211, Name = "Software Functionality" } };
    int value= list.OrderByDescending(a => a.Order).ThenBy(a => a.Name).ToList().First().Id;
    Console.WriteLine (value);
}

public class Project 
{
    public int Order {get;set;}
    public int Id {get;set;}
    public string Name {get;set;}
}
  

但是,如果你确实需要它作为一个字符串:为什么它不像这样工作?

查看CompareOptions枚举。更具体地说:CompareOptions.IgnoreSymbols

  

表示字符串比较必须忽略符号,例如空格字符,标点符号,货币符号,百分号,数学符号,&符号等等上。这也解释了here

这实际上使您的-9成为9

您可以通过创建自己的比较器并将其传递给您所需的内容轻松绕过这个:

public class CustomComparer : IComparer<string>
{
    public int Compare(string x,string y)
    {
        return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.Ordinal);
    }
}

可以用作

new[] {"1", "-9"}.OrderByDescending(x => x, new CustomComparer())

答案 1 :(得分:-1)

我试图重建你的问题。这是我的代码(LinqPad),它可以正常工作:

void Main()
{
    List<ProgramA> progs = new List<ProgramA>{
        new ProgramA("Summary", 1, 147),
        new ProgramA("Software Functionality", -9, 211)
        };

    int value= progs.OrderByDescending(a => a.Order).ThenBy(a => a.Name).ToList().First().ID;

    value.Dump();

}

// Define other methods and classes here
class ProgramA
{
    private string sName = string.Empty;
    private int iOrder = 0;
    private int iID = 0;

    public ProgramA(string _Name, int _Order, int _ID)
    {
        sName = _Name;
        iOrder = _Order;
        iID = _ID;
    }

    public string Name
    {
        get {return sName;}
        set {sName = value;}
    }

    public int Order
    {
        get {return iOrder;}
        set {iOrder = value;}
    }

    public int ID
    {
        get {return iID;}
        set {iID = value;}
    }
}

返回: 147

<强> [编辑]

@DStanley它存储为&#34; 1&#34;和&#34; -9&#34;在列表中 - user1989 6分钟前

如果 Order 存储为字符串值,您可以尝试将其转换为整数:

    int value= progs.OrderByDescending(a => Convert.ToInt32(a.Order)).ThenBy(a => a.Name).ToList().First().ID;

答案 2 :(得分:-3)

string value = projectA.OrderByDescending(a =&gt; a.Order).ThenBy(a =&gt; a.Name)。ToList()。First()。ID.ToString();

OrderByDescending =&gt;命令 输出 - -9,1

选择第一个元素 - 9 = 211.逻辑是正确的。