如何将具有int,string属性的对象列表转换为具有所有字符串属性的对象列表?
例如:我有一个具有多种属性的对象列表,如{ int Cd, string Name}
我想转换为所有字符串属性都喜欢{string Cd, string Cd}
答案 0 :(得分:0)
您可以使用@MichaWiedenmann建议的LINQ Select
,并创建一个具有Cd
和Name
属性的新匿名类。 x.Cd.ToString()
部分正在将Cd
内的每个对象的整数属性list
转换为字符串:
List<myObject> list = new List<myObject>()
{
new myObject() {Cd=1,Name="John" },
new myObject() {Cd=2,Name="Peter" },
new myObject() {Cd=3,Name="David" }
};
var newList = list.Select(x => new { Cd = x.Cd.ToString(), Name = x.Name }).ToList();
答案 1 :(得分:0)
也许你可以使用以下反思方法。
这是一个包含所有相关属性和字段及其值的类:
public class StringType
{
public StringType(IDictionary<MemberInfo, string> allPropertiesAndFields)
{
this.PropertiesAndFields = allPropertiesAndFields;
this.PropertyFieldNamesAndValues = allPropertiesAndFields.ToDictionary(m => m.Key.Name, m => m.Value);
}
private IDictionary<MemberInfo, string> PropertiesAndFields { get; set; }
private IDictionary<string, string> PropertyFieldNamesAndValues { get; set; }
public string GetValue(string propertyOrFieldName)
{
bool isKnown = PropertyFieldNamesAndValues.TryGetValue(propertyOrFieldName, out string value);
if (isKnown)
return value;
return null;
}
// if you want to know all informations about the property or field like type
public MemberInfo GetMemberInfo(string propertyOrFieldName)
{
MemberInfo memberInfo = PropertiesAndFields.Keys.FirstOrDefault(mi => mi.Name == propertyOrFieldName);
return memberInfo;
}
}
现在你需要一个转换器方法:
public static StringType ConvertSomeClassToString(Object instance)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; // maybe as parameter, cgange accordingly
Type t = instance.GetType();
PropertyInfo[] properties = t.GetProperties(bindingFlags);
FieldInfo[] fields = t.GetFields(bindingFlags);
var propertyMemberValues = properties.Select(p => new { Member = (MemberInfo) p, Value = p.GetValue(instance) });
var fieldMemberValues = fields.Select(f => new { Member = (MemberInfo) f, Value = f.GetValue(instance) });
Dictionary<MemberInfo, string> dict = propertyMemberValues
.Concat(fieldMemberValues)
.ToDictionary(m => m.Member, m => m.Value?.ToString());
return new StringType(dict);
}
这会将任何类型的实例转换为StringType
。这是一个样本:
var list = new List<SomeClass>() { new SomeClass { Name = "foo", Cd = 4711 } };
Converter<Object, StringType> converter = ConvertSomeClassToString;
List<StringType> stringItemList = list.ConvertAll(converter);
StringType st = stringItemList.First();
string valueOfCD = st.GetValue("Cd"); // "4711"