我是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满足此条件?
发布于 2014-02-14 13:52:21
var lstProfileSearchResultEntity =
query.Select(i => new ProfileSearchResultEntity
{
Id = i.Id,
Name = i.LastName + "," + " " + i.FirstName +
(string.IsNullOrEmpty(i.DisplayName) ? "" : " - " + i.DisplayName)
}).ToList();发布于 2014-02-14 13:52:16
这就是它:
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;
});我要展示的是,您可以编写一个函数来初始化新选择的对象。
https://stackoverflow.com/questions/21771653
复制相似问题