简体   繁体   English

返回类的所有属性,而不是null c#

[英]Return all properties of class, not null c#

I've been looking and found this which describes to return a bool if value is null . 我一直在寻找,发现这说明如果value为null,则返回布尔值 The code, I'm using is from this snippet Client client = new Client{ FirstName = "James"}; 我正在使用的代码来自此片段Client client = new Client {FirstName =“ James”};

client.GetType().GetProperties()
.Where(pi => pi.GetValue(client) is string)
.Select(pi => (string) pi.GetValue(client))
.Any(value => string.IsNullOrEmpty(value));

But instead of returning if the value is null or not (the bool) I would like to retrieve all the properties values where they are not null. 但是,我不想在值不为null的情况下返回(布尔值),而是要检索所有不为null的属性值。

I've tried making changes to the code, but unsuccessful. 我尝试对代码进行更改,但未成功。

Many thanks 非常感谢

EDIT 编辑

public class Client
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   //...
}

Client client = new Client();
client.FirstName = "James";
client.LastName = "";

Using my 'Client' class, I would like to iterate over all the properties within my class, and where the value isn't null or empty string, I would return the value, in this example, I would only return a string "James". 使用“ Client”类,我想遍历类中的所有属性,并且该值不是null或空字符串时,我将返回该值,在本示例中,我将仅返回字符串“ James” ”。

Hope that makes sense. 希望有道理。

There are some issues: 有一些问题:

return myObject.GetType().GetProperties()
.Where(pi => pi.GetValue(myObject) is string) // this wastes time getting the value
.Select(pi => (string) pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value)); //  Any will return a bool

So change this to: 因此,将其更改为:

return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string)) // check type
.Select(pi => (string)pi.GetValue(myObject)) // get the values
.Where(value => !string.IsNullOrEmpty(value)); // filter the result (note the !)

Also, ensure that your properties are properties and not fields. 另外,请确保您的属性是属性而不是字段。

Use Where instead of Any . 使用Where而不是Any Also you were missing an ! 你也错过了! at !string.IsNullOrEmpty(value) . !string.IsNullOrEmpty(value)

I modified your code to return a dictionary with property values indexed by name. 我修改了您的代码,以返回带有按名称索引的属性值的字典。

var stringPropertyValuesByName = client.GetType().GetProperties()
    .Where(pi => pi.PropertyType == typeof(string)) // use type check as Steve Harris suggested 
    .Select(pi => new { Val = (string) pi.GetValue(client), Name = pi.Name })
    .Where(pi => !string.IsNullOrEmpty(pi.Val))
    .ToDictionary(pi => pi.Name, pi => pi.Val);

C# Fiddle C#小提琴

If you want to get all not null properties that are also not empty strings i suggest: 如果要获取所有也不为空字符串的非null属性,我建议:

using System;
using System.Linq;

class Cls
{
    public string Prop1 {get; set;}

    public object Prop2 {get; set;}

    public int Prop3 {get; set;}

    public string Prop4 {get; set;}

}

public class Program
{
    public static void Main()
    {
        var obj = new Cls() { Prop1 = "abc", Prop3 = 5 };

        var props = obj
            .GetType()
            .GetProperties()
            .Select(p => p.GetValue(obj))
            .Where(x => x != null || ( x is string && (string)x != ""))
            .ToList();

        Console.WriteLine(string.Join(",", props));
    }
}

produces: 生产:

abc,5 ABC,5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM