LINQ中的Coalesce / IsNull功能

时间:2011-09-23 16:00:24

标签: c# .net linq c#-4.0 .net-4.0

如果某个属性具有某个特定条件,例如/ empty

,我怎样才能使某个属性返回某个字符串
public class Person
{
  public string Name{get;set;}
  publc string MiddleName{get;set;}
  public string Surname{get;set;}
  public string Gender{get;set;}
}

List<Person> people = repo.GetPeople();
List<Person> formatted = people.GroupBy(x=>x.Gender).//?? format Gender to be a certain string eg/"Not Defined" if blank 

3 个答案:

答案 0 :(得分:5)

people.GroupBy(x=>x.Gender ?? "Not Available").ToList();

更新:(捕捉空字符串)

people.GroupBy(x=> String.IsNullOrWhiteSpace(x.Gender) ? "None" : x.Gender).ToList();

答案 1 :(得分:0)

如果这是当地的情况,我会修复null?在它需要的地方。

如果需要更通用的解决方案,我建议。我是直接在getter(或者setter,如果需要)中修复它。

 private string _gender;
 public string Gender
 {
    get {
        string val = 
           (!string.IsNullOrEmpty(_gender) ? _gender : "[Not decided yet]");
        return val; 
    }
    set { _gender = value; }
 }

在整个测试样本程序中,

public class Nullable
{
    public class Person
    {
      private string _gender;
      public string Gender
      {
          get {
              string val = 
                 (!string.IsNullOrEmpty(_gender) ? _gender : "[Not decided yet]");
              return val; 
          }
          set { _gender = value; }
      }

      public string Name { get; set; }
      public string MiddleName { get; set; }
      public string Surname { get; set; }
    }

    static void Main()
    {
        List<Person> p = new List<Person>();
        p.Add(new Person() { Name = "John Doe", Gender = "Male" });
        p.Add(new Person() { Name = "Jane Doe", Gender = "Female" });
        p.Add(new Person() { Name = "Donna Doe", Gender = "Female" });
        p.Add(new Person() { Name = "UnDoe",  });

        // test 1
        foreach (var item in p.GroupBy(x => x.Gender))
            Console.WriteLine(item.Count() + " " + item.Key);

        Console.WriteLine(Environment.NewLine);

        //test 2
        foreach (var item in p)
            Console.WriteLine(item.Name + "\t" + item.Gender);

        Console.ReadLine();
    }
}

答案 2 :(得分:0)

尝试这样的事情(我使用int作为属性类型):

public class Widget
{
  private int? MyPropertyBackingStore ;
  public int MyProperty
  {
    get
    {
      int value = 0 ; // the default value
      if ( this.MyPropertyBackingStore.HasValue && this.MyPropertyBackingStore > 0 )
      {
        value = this.MyPropertyBackingStore.Value ;
      }
      return value ;
    }
    set
    {
      this.MyPropertyBackingStore = value ;
    }
  }
}

或者,因为它是一个属性所以控制如何设置值/什么值是微不足道的:只需调整settor中的属性值。

public class Widget
{
  private int MyPropertyBackingStore ;
  public int MyProperty
  {
    get
    {
      return this.MyPropertyBackingStore ;
    }
    set
    {
      if ( this.MyPropertyBackingStore.HasValue && this.MyPropertyBackingStore > 0 )
      {
        this.MyPropertyBackingStore = value ;
      }
      else
      {
        this.MyPropertyBackingStore = -1 ;
      }
    }
  }
}