[英]Return all properties of class, not null c#
我一直在寻找,发现这说明如果value为null,则返回布尔值 。 我正在使用的代码来自此片段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));
但是,我不想在值不为null的情况下返回(布尔值),而是要检索所有不为null的属性值。
我尝试对代码进行更改,但未成功。
非常感谢
编辑
public class Client
{
public string FirstName { get; set; }
public string LastName { get; set; }
//...
}
Client client = new Client();
client.FirstName = "James";
client.LastName = "";
使用“ Client”类,我想遍历类中的所有属性,并且该值不是null或空字符串时,我将返回该值,在本示例中,我将仅返回字符串“ James” ”。
希望有道理。
有一些问题:
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
因此,将其更改为:
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 !)
另外,请确保您的属性是属性而不是字段。
使用Where
而不是Any
。 你也错过了!
在!string.IsNullOrEmpty(value)
。
我修改了您的代码,以返回带有按名称索引的属性值的字典。
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);
如果要获取所有也不为空字符串的非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));
}
}
生产:
ABC,5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.