Reputation: 658
I have following 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"; } }
}
I want to get the value of each property in Linq
query.
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();
}
Problem is how to get value of each property by p.GetValue
in linq
.
Upvotes: 3
Views: 4933
Reputation: 45272
var query = from p in user.GetType().GetProperties()
select p.GetValue(user).ToString();
The call to ToString()
is required because you are wanting an enumerable of strings, not an enumerable of objects. However, this does run the risk of a Null Reference error in the case where a property value equals null
A safer alternative is this:
var query = user.GetType()
.GetProperties()
.Select(p => p.GetValue(user))
.Select(o => Object.ReferenceEquals(o, null)
? default(string)
: o.ToString()
);
Upvotes: 8