C# 如果字段不为空,请选择该字段

C# 如果字段不为空,请选择该字段,c#,linq,entity-framework,linq-to-entities,C#,Linq,Entity Framework,Linq To Entities,我有一个实体,它有两个字段作为名称 public class Place { string EnglishName {get; set;} string LocalizedName {get; set;} ... } 默认情况下,我希望选择LocalizedName,但如果LocalizedName为null,则选择EnglishName。 是否可以在linq中编写如下查询: from place in _context.Places where place.Slug

我有一个实体,它有两个字段作为名称

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 }

是的,它会起作用的。完整示例:

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

此代码将从列表中搜索slug,并返回第一个匹配的LocalizedName。如果LocalizedName为null,它将返回该位置的EnglishName

string placeName = _context.Places
                           .Where(place => place.Slug == slug)
                           .Select(place => place.LocalizedName ?? 
                            place.EnglishName).FirstOrDefault();

它不起作用了?请报告任何问题。这可能取决于上下文。位置是IQueryable还是IEnumerable。你我应该试试这个,然后发布完整的错误信息。我没有试过,我只是在看一些类似的东西。嘿,downvoter,downvoter的原因是什么?这个代码将从列表中搜索slug,并返回第一个匹配的LocalizedName,如果LocalizedName为空,它将返回该位置的EnglishName。你能把它放在你的答案中吗?