2012-08-22 25 views
0

我有這樣的LINQ語法我填充LINQ列表<string>,但項目的順序是隨機的

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: "[email protected]" string 
     dni:"DNI 12312322" string 
    item 2: 
      dni:"DNI 12312872" string 
      mail:"[email protected]" string 
      nombre: "Peuchele Ruben" string 
      id: "   2" string 

     item 3: 
      id: "   3" string 
      nombre: "la momia Blanca" string 
      mail: "[email protected]" string 
      dni: "DNI 45612322" string 

項2具有第一DNI然後郵寄。其他項目有第一個ID,然後名稱

爲什麼發生這種情況?

+2

你應該匿名代碼 – Andre

+1

這個帖子是真的* *很難讀 - 試圖從你的調試器轉儲是一場噩夢制定出每個元素的內容。請重新格式化它。 –

回答

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

不知道爲什麼會發生(雖然我認爲項目在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不支持與多個元素列表初始化。

+0

我需要這些值是一個字符串列表,以填充jqgrid。 –

+0

請參閱我的編輯。 –

+0

要將其轉換爲IENUMERABLE,我必須通過每個項目並手動生成新列表? –