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

时间:2014-07-24 11:55:32

标签: 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 == slug
select new { Name = !string.IsNullOrEmpty(place.LocalizedName) 
                    ? place.LocalizedName 
                    : place.EnglishName }

2 个答案:

答案 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();