2010-11-23 46 views
38

tengo el código de abajo:No se puede convertir implícitamente el tipo 'System.Collections.Generic.IEnumerable <AnonymousType # 1>' a 'System.Collections.Generic.List <string>

List<string> aa = (from char c in source 
        select new { Data = c.ToString() }).ToList(); 

Pero ¿qué pasa con

List<string> aa = (from char c1 in source 
        from char c2 in source 
        select new { Data = string.Concat(c1, ".", c2)).ToList<string>(); 

Mientras compilación error al obtener

no se puede convertir implícitamente el tipo 'System.Collections.Generic.List<AnonymousType#1>'-'System.Collections.Generic.List<string>'

Necesita ayuda.

+0

¿Cuál es la tarea final y cuál es la fuente? – abatishchev

+0

En cuanto a su última edición menciona dos veces la misma fuente, vea mi respuesta n. ° 2: puede ayudarlo. – abatishchev

Respuesta

47
IEnumerable<string> e = (from char c in source 
         select new { Data = c.ToString() }).Select(t = > t.Data); 
// or 
IEnumerable<string> e = from char c in source 
         select c.ToString(); 
// or 
IEnumerable<string> e = source.Select(c = > c.ToString()); 

A continuación, puede llamar ToList():

List<string> l = (from char c in source 
        select new { Data = c.ToString() }).Select(t = > t.Data).ToList(); 
// or 
List<string> l = (from char c in source 
        select c.ToString()).ToList(); 
// or 
List<string> l = source.Select(c = > c.ToString()).ToList(); 
+0

Que tal esto –

+2

@ priyanka.sarkar_2: Debe usar 'Select (x => x.Data) .ToList()' para seleccionar la lista de dichos datos. – abatishchev

2

tratar

var lst= (from char c in source select c.ToString()).ToList(); 
+0

No puedo usar var ... tiene que ser List por algún motivo –

+0

De esta manera obtendrá 'List ' – abatishchev

+0

@Rover: no, .ToList() convierte IEnumerable en List

11

Si usted quiere que sea List<string>, deshacerse del tipo anónimo y añadir una llamada .ToList() :

List<string> list = (from char c in source 
        select c.ToString()).ToList(); 
+1

¿Qué pasa con la lista aa = (desde char c1 en la fuente desde char c2 en la fuente seleccione nuevo {Data = string.Concat (c1, ".", C2)). ToList (); –

2

Si tiene origen como una cadena como "abcd" y quiere producir una lista como esta: entonces

{ "a.a" }, 
{ "b.b" }, 
{ "c.c" }, 
{ "d.d" } 

llamar:

List<string> list = source.Select(c => String.Concat(c, ".", c)).ToList(); 
1

Creo que las respuestas están por debajo

List<string> aa = (from char c in source 
        select c.ToString()).ToList(); 

List<string> aa2 = (from char c1 in source 
        from char c2 in source 
        select string.Concat(c1, ".", c2)).ToList(); 
Cuestiones relacionadas