10

次のようなクラスのリストがある場合:

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

ラムダ式を使用して、次のようにクラスのリスト内の属性を文字列結合できますか?

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

4

3 に答える 3

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

ToString をオーバーライドすることもできます。

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

...そして、呼び出しは非常に単純です(.Net 4.0):

string.Join(", ", newInfo);
于 2012-05-10T22:08:07.493 に答える
9
String.Join(", ", newInfo.Select(i=>i.Name+"("+i.Count+")") );
于 2012-05-10T22:07:38.270 に答える
1

次のように使用できます

このような特定のタイプを返すことができます

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

または、このような匿名型を取得できます

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

                 })
于 2014-05-23T09:27:16.817 に答える