Asp.net 对给定场景使用Linq
我是LINQ的新手,我的TL给了我一个要求,我可以在几秒钟内完成,因为这是一个基本的要求,我想把代码转换成LINQ,请帮助我Asp.net 对给定场景使用Linq,asp.net,asp.net-mvc,lambda,Asp.net,Asp.net Mvc,Lambda,我是LINQ的新手,我的TL给了我一个要求,我可以在几秒钟内完成,因为这是一个基本的要求,我想把代码转换成LINQ,请帮助我 foreach (var item in query) { profileSearchResultEntity = new ProfileSearchResultEntity(); profileSearchResultEntity.Id = item.ProfileId;
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满足此条件???这里是:
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;
});
我想展示一下,您可以编写一个函数来初始化新选择的对象。非常感谢您的回复Anthony,现在我开始使用LINQ扩展方法,它可以帮助批量查询MySQL。非常感谢Brad的回复。
var lstProfileSearchResultEntity =
query.Select(i => new ProfileSearchResultEntity
{
Id = i.Id,
Name = i.LastName + "," + " " + i.FirstName +
(string.IsNullOrEmpty(i.DisplayName) ? "" : " - " + i.DisplayName)
}).ToList();