我有以下类(class)。
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"; } }
}
我想在 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();
}
问题是如何在linq
中通过p.GetValue
获取每个属性的值。
最佳答案
var query = from p in user.GetType().GetProperties()
select p.GetValue(user).ToString();
调用 ToString()
是必需的,因为您需要可枚举的字符串,而不是可枚举的对象。但是,在属性值等于 null
一个更安全的选择是:
var query = user.GetType()
.GetProperties()
.Select(p => p.GetValue(user))
.Select(o => Object.ReferenceEquals(o, null)
? default(string)
: o.ToString()
);
关于c# - 如何使用 Linq 查询和 IEnumerable 获取类属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492812/