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

标签 c# .net linq ienumerable

我有以下类(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/

相关文章:

c# - 为并发锁定 HashSet

c# - 使用 LINQ 进行两个查询的完全外部联接的更好方法? C#

c# - 当输出参数是一个类时,如何在 C++ 中调用 COM 方法?

c# - 处理 C# WebService 异常

c# - 如何只刷新 HTML 页面的特定部分?

c# - 动态创建数据集并传递给 ReportViewer

c# - 在 c# 中从 vs2008 迁移到 vs2012 的 Crystal 报表上未找到文件异常未处理

linq - 如何使用 Linq 和 Entity Framework 连接两个可连接对象?

c# - 如何从字符串列表中获取字符串?

c# - 使用SSIS将文件上传到共享点文档库时获取远程服务器返回错误: (403) Forbidden.错误