2012-05-10 4 views
7

Se ho un elenco di alcuni classe come questa:String Partecipa Usando un'espressione 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 }} 
}; 

un'espressione lambda Può essere usato per stringa di unire gli attributi nella lista delle classi in questo modo:

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

risposta

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

Si potrebbe anche ignorare ToString.

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

... e poi la chiamata è morto semplice (NET 4.0):

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

Se fosse dove il mio progetto, vorrei andare con qualcosa di simile. – asawyer

+0

Grazie Austin! –

+0

+1, sicuramente raccomandare l'override di 'ToString()' in questo caso. – yamen

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

è possibile utilizzare come come seguire

è possibile restituire un tipo specifico come questo

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

Oppure È possibile recuperare tipo anonimo come questo

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 

       }) 
Problemi correlati