Question

I have this linq syntax

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
                                  }
                           }
            };

The problem is that the value of each list in cell property has random order of items.

Example result:

        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

The item 2 has first dni and then mail. the other items has first id and then name

why happend this?

Was it helpful?

Solution 2

The solution:

 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
            };

OTHER TIPS

Not sure why it happens (although I think that the enumeration order of items in a List<T> is not guaranteed to be stable), but it can be solved by using named values:

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

Additional benefit: the receiving side knows better what it's dealing with.


EDIT (after your comment)

Try your luck with

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

But you'll have to convert to IEnumerable first, EF does not support list initializers with multiple elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top