如何使用Linq查询和IEnumerable获取类属性的值

Ahs*_*san 1 .net c# linq ienumerable

我有下课.

public class User
{
    public User() { }
    public int Id; 
    public string Name; 
    public string Surname; 
    public string PhoneMobil; 
    public string SecondaryPhone; 
    public string Job; 
    public string Sex; 
    public string DepartmentName; 

    public int ID { get{return Id;} set { Id = 111; } }
    public string NAME { get { return Name; } set { Name = "ahsan riaz 1111"; } }
    public string SURNAME { get { return Surname; } set { Surname = "ahsan 1111 riaz"; } }
    public string PHONEMOBIL { get { return PhoneMobil; } set { PhoneMobil = "riaz ahsan"; } }
    public string SECONDARYPHONE { get { return SecondaryPhone; } set { SecondaryPhone = "How are you?"; } }
    public string JOB { get { return Job; } set { Job = "How do you do?"; } }
    public string SEX { get { return Sex; } set { Sex = "What and How do you do?"; } }
    public string DEPARTMENTNAME { get { return DepartmentName; } set { DepartmentName = "ahsan riaz"; } }
}
Run Code Online (Sandbox Code Playgroud)

我想在Linq查询中获取每个属性的值.

public static IEnumerable<string> Suggestions<T>(this T user) where T : class
{
    var query = from p in user.GetType().GetProperties()
                select p.GetValue(/* it takes the name of property, i cannot provided name for each property*/);
    return query.AsEnumerable();
}
Run Code Online (Sandbox Code Playgroud)

问题是如何让每个属性的值p.GetValuelinq.

And*_*erd 5

 var query = from p in user.GetType().GetProperties()
                    select p.GetValue(user).ToString();
Run Code Online (Sandbox Code Playgroud)

调用ToString()是必需的,因为您需要一个可枚举的字符串,而不是一个可枚举的对象.但是,在属性值等于的情况下,这确实存在Null Reference错误的风险null

一个更安全的替代方案是:

var query = user.GetType()
                .GetProperties()
                .Select(p => p.GetValue(user))
                .Select(o => Object.ReferenceEquals(o, null) 
                          ? default(string) 
                          : o.ToString()
                       );
Run Code Online (Sandbox Code Playgroud)