2012-02-09 8 views
18

Tengo la siguiente consulta:Agregar elementos a la lista de LINQ var

public class CheckItems 
    { 
     public String Description { get; set; } 
     public String ActualDate { get; set; } 
     public String TargetDate { get; set; } 
     public String Value { get; set; } 
    } 



    List<CheckItems> vendlist = new List<CheckItems>(); 

    var vnlist = (from up in spcall 
       where up.Caption == "Contacted" 
         select new CheckItems 
         { 
          Description = up.Caption, 
          TargetDate = string.Format("{0:MM/dd/yyyy}", up.TargetDate), 
          ActualDate = string.Format("{0:MM/dd/yyyy}", up.ActualDate), 
          Value = up.Value 
         }).ToList(); 

// A continuación, cuando intento agregar vnlist a vendlist, me sale un error ya que no puedo añadir esto a la lista consigo y el error diciendo que tengo algunos argumentos no válidos

  vendlist.Add(vnlist); 
+1

Puede eliminar la llamada .ToList. AddRange toma un enumerable, y lo enumerará todo por sí mismo. ToList está haciendo una lista, rellenándola y descartándola inmediatamente. Por qué perder el tiempo en eso. – Servy

Respuesta

28

Si es necesario agregar cualquier colección IEnumerable de elementos de la lista es necesario utilizar AddRange.

vendlist.AddRange(vnlist); 
+0

No es solo una "matriz", sino cualquier IEnumerable. –

+0

Sí, eso es lo que quiero decir. Gracias, corregido. – Samich

3

Creo que intenta agregar una lista completa en lugar de una sola instancia de CheckItems. no tengo un compilador de C# aquí, pero tal vez en lugar de AddRange añada obras:

vendlist.AddRange(vnlist); 
4

o combinarlos ...

vendlist.AddRange((from up in spcall 
       where up.Caption == "Contacted" 
         select new CheckItems 
         { 
          Description = up.Caption, 
          TargetDate = string.Format("{0:MM/dd/yyyy}", up.TargetDate), 
          ActualDate = string.Format("{0:MM/dd/yyyy}", up.ActualDate), 
          Value = up.Value 
         }).ToList()); 
0

Aquí hay una forma sencilla de hacer esto:

List<CheckItems> vendlist = new List<CheckItems>(); 

var vnlist = from up in spcall 
       where up.Caption == "Contacted" 
       select new 
        { 
         up.Caption, 
         up.TargetDate, 
         up.ActualDate, 
         up.Value 
        }; 

foreach (var item in vnlist) 
      { 
       CheckItems temp = new CheckItems(); 
       temp.Description = item.Caption; 
       temp.TargetDate = string.Format("{0:MM/dd/yyyy}", item.TargetDate); 
       temp.ActualDate = string.Format("{0:MM/dd/yyyy}", item.ActualDate); 
       temp.Value = item.Value; 

       vendlist.Add(temp); 
      } 
Cuestiones relacionadas