0

我有这个 linq 语法

var jsonData = new
            {
                total = 1,
                page = 1,
                records = per.Count(),
                rows = 
                           from r in per
                           select new
                           {
                               id = r.id,
                               cell = new List<string>()
                                  {
                                       SqlFunctions.StringConvert((double)  r.id),
                                       r.nombre,
                                       r.mail,
                                       r.documento
                                  }
                           }
            };

问题是单元格属性中每个列表的值具有随机的项目顺序。

示例结果:

        item 1:  id:"         1"    string
        nombre:"Medina Teto"    string
        mail: "soyelteto@hotmail.com"   string
        dni:"DNI 12312322"  string
    item 2:
            dni:"DNI 12312872"  string
            mail:"elancho@hotmail.com"  string
            nombre: "Peuchele Ruben"    string
            id: "         2"    string

        item 3:
            id: "         3"    string
            nombre: "la momia Blanca"   string
            mail: "soylamomiabuena@hotmail.com" string
            dni: "DNI 45612322" string

项目 2 先是 dni,然后是邮件。其他项目具有第一个 ID,然后是名称

为什么会这样?

4

2 回答 2

1

不知道为什么会发生(虽然我认为 a 中项目的枚举顺序List<T>并不能保证是稳定的),但是可以通过使用命名值来解决:

cell = new
{
    dni = SqlFunctions.StringConvert((double)  r.id),
    nombre = r.nombre,
    mail = r.mail,
    documento = r.documento
}

额外的好处:接收方更清楚它正在处理什么。


编辑(在您发表评论后)

试试你的运气

cell = new SortedList<int,string>
{
    { 1, r.id.ToString() },
    { 2, r.nombre },
    { 3, r.mail },
    { 4, r.documento }
}

但是您必须先转换为IEnumerable,EF 不支持具有多个元素的列表初始值设定项。

于 2012-08-22T20:46:37.700 回答
0

解决方案:

 var rows = per.AsEnumerable()
                        .Select(r => new
                           {
                               id = r.id,
                               cell = new[]
                                  {
                                       r.id.ToString(),
                                       r.nombre,
                                       r.mail,
                                       r.documento
                                  }
                           }).ToArray();

            var jsonData = new
            {
                total = 1,
                page = 1,
                records = per.Count(),
                rows
            };
于 2012-08-24T11:17:12.140 回答