使用 lambda 表达式进行字符串联接

本文关键字:字符串 lambda 表达式 使用 | 更新日期: 2023-09-27 18:33:44

如果我有这样的类列表:

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

是否可以使用 Lambda 表达式来字符串连接类列表中的属性,如下所示:

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

使用 lambda 表达式进行字符串联接

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);
String.Join(", ", newInfo.Select(i=>i.Name+"("+i.Count+")") );

你可以像下面这样使用

您可以像这样返回特定类型

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