我有下课。
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();
}
问题是如何在p.GetValue
中linq
获取每个媒体资源的价值。
答案 0 :(得分:5)
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()
);