我有一个实体,其名称有两个字段。
public class Place
{
string EnglishName {get; set;}
string LocalizedName {get; set;}
...
}
默认情况下,我想选择LocalizedName,但如果LocalizedName为null,则选择EnglishName。 是否可以在linq中编写这样的查询:
from place in _context.Places
where place.Slug == slug
select new { Name = !string.IsNullOrEmpty(place.LocalizedName)
? place.LocalizedName
: place.EnglishName }
答案 0 :(得分:2)
是的,它会起作用。完整的例子:
public class Place
{
public string EnglishName { get; set; }
public string LocalizedName { get; set; }
public string Slug { get; set; }
}
void Main()
{
var places = new List<Place>
{
new Place { LocalizedName = "Localized1", EnglishName = "English1", Slug = "Slug" },
new Place { LocalizedName = null, EnglishName = "English2", Slug = "Slug" },
new Place { LocalizedName = "Localized3", EnglishName = "English3", Slug = "Slug" },
new Place { LocalizedName = null, EnglishName = "English4", Slug = "Slug" },
};
var slug = "Slug";
var names =
from place in places
where place .Slug == slug
select new { Name = !string.IsNullOrEmpty(place.LocalizedName )
? place.LocalizedName
: place.EnglishName };
foreach (var name in names)
Console.WriteLine(name);
}
// Displays:
// Localized1
// English2
// Localized3
// English4
答案 1 :(得分:1)
此代码将从列表中搜索slug并返回第一个匹配的LocalizedName。如果LocalizedName
为空,则会返回该地点的EnglishName
。
string placeName = _context.Places
.Where(place => place.Slug == slug)
.Select(place => place.LocalizedName ??
place.EnglishName).FirstOrDefault();