2012-05-10 9 views
7

Si tengo una lista de algunos clase como esta:cadena Únete Usando una expresión lambda

class Info { 
    public string Name { get; set; } 
    public int Count { get; set; } 
} 

List<Info> newInfo = new List<Info>() 
{ 
    {new Info { Name = "ONE", Count = 1 }}, 
    {new Info { Name = "TWO", Count = 2 }}, 
    {new Info { Name = "SIX", Count = 6 }} 
}; 

Puede una expresión Lambda ser utilizado para encadenar unirse a los atributos en la lista de clases de la siguiente manera:

"ONE(1), TWO(2), SIX(6)"

Respuesta

14
string.Join(", ", newInfo.Select(i => string.Format("{0}({1})", i.Name, i.Count))) 

también podría invalidar ToString.

class Info 
{ 
    .... 
    public override ToString() 
    { 
     return string.Format("{0}({1})", Name, Count); 
    } 
} 

... y entonces la llamada es muy simple (.Net 4.0):

string.Join(", ", newInfo); 
+0

Si fuera mi proyecto, iría con algo como esto. – asawyer

+0

¡Gracias, Austin! –

+0

+1, definitivamente recomendamos anular 'ToString()' en este caso. – yamen

8
String.Join(", ", newInfo.Select(i=>i.Name+"("+i.Count+")")); 
2

se puede utilizar como como seguir

Usted puede devolver un tipo específico como éste

Patient pt = dc.Patients.Join(dc.PatientDetails, pm => pm.PatientId, pd => pd.PatientId, 
         (pm, pd) => new 
         { 
          pmm = pm, 
          pdd = pd 
         }) 
         .Where(i => i.pmm.PatientCode == patientCode && i.pmm.IsActive || i.pdd.Mobile.Contains(patientCode)) 
         .Select(s => new Patient 
         { 
          PatientId = s.pmm.PatientId, 
          PatientCode = s.pmm.PatientCode, 
          DateOfBirth = s.pmm.DateOfBirth, 
          IsActive = s.pmm.IsActive, 
          UpdatedOn = s.pmm.UpdatedOn, 
          UpdatedBy = s.pmm.UpdatedBy, 
          CreatedOn = s.pmm.CreatedOn, 
          CreatedBy = s.pmm.CreatedBy 
         }) 

O Puede recuperar el tipo anónimo como este

var patientDetails = dc.Patients.Join(dc.PatientDetails, pm => pm.PatientId, pd => pd.PatientId, 
       (pm, pd) => new 
       { 
        pmm = pm, 
        pdd = pd 
       }) 
       .Where(i => i.pmm.PatientCode == patientCode && i.pmm.IsActive || i.pdd.Mobile.Contains(patientCode)) 
       .Select(s => new 
       { 
        PatientId = s.pmm.PatientId, 
        PatientCode = s.pmm.PatientCode, 
        DateOfBirth = s.pmm.DateOfBirth, 
        IsActive = s.pmm.IsActive,      
        PatientMobile = s.pdd.Mobile, 
        s.pdd.Email, 
        s.pdd.District, 
        s.pdd.Age, 
        s.pdd.SittingId 

       }) 
Cuestiones relacionadas