我是LINQ的新手,我的TL给了我一个要求,我能够在几秒钟内完成它,因为它是一个基本的,我希望将代码转换为LINQ,请帮助我。
foreach (var item in query)
{
profileSearchResultEntity = new ProfileSearchResultEntity();
profileSearchResultEntity.Id = item.ProfileId;
if (String.IsNullOrEmpty(item.DisplayName))
{
profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName;
}
else
{
profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName +" "+"-"+" "+ item.DisplayName;
}
lstProfileSearchResultEntity.Add(profileSearchResultEntity);
}
return lstProfileSearchResultEntity;
如何使用LINQ或Lambda ????
来满足此条件答案 0 :(得分:1)
var lstProfileSearchResultEntity =
query.Select(i => new ProfileSearchResultEntity
{
Id = i.Id,
Name = i.LastName + "," + " " + i.FirstName +
(string.IsNullOrEmpty(i.DisplayName) ? "" : " - " + i.DisplayName)
}).ToList();
答案 1 :(得分:0)
这是:
return query.Select(item =>
{
var profileSearchResultEntity = new ProfileSearchResultEntity{Id = item.ProfileId};
if (String.IsNullOrEmpty(item.DisplayName))
{
profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName;
}
else
{
profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName + " " +
"-" + " " + item.DisplayName;
}
return profileSearchResultEntity;
});
我想表明你可以编写一个函数来初始化新选择的对象。