各位前輩好
有個只有bool property 的class如下
public class CRUDModel
{
public bool Create { get; set; }
public bool Read { get; set; }
public bool Update { get; set; }
public bool Delete { get; set; }
}
有三個object如下,要將他們union成一個新的obj怎麼做會比較好?
var obj1 = new CRUDModel{Create =true};
var obj2 = new CRUDModel{Read =true};
var obj3 = new CRUDModel{Delete =true};
目前的作法是將三個加入List內,然後用ForEach對每個property下OR,把值給new obj,但感覺不是很好,屬性現在只有四個,要是有十個二十個就要寫那麼多OR。
var objs = new List<CRUDModel>();
objs.Add(obj1);
objs.Add(obj2);
objs.Add(obj3);
var objNew = new CRUDModel();
objs.ForEach(e => {
objNew.Create = objNew.Create||e.Create;
objNew.Read = objNew.Read||e.Read;
objNew.Update = objNew.Update||e.Update;
objNew.Delete = objNew.Delete||e.Delete;
});
是可以給class一個Add Method,不過想到的做法還是像上面一樣一個個OR......
用匿名
var objTotal = new {
obj1 = new CRUDModel{Create =true},
obj2 = new CRUDModel{Read =true},
obj3 = new CRUDModel{Delete =true}
}
太神啦!居然有這種操作!雖然這題已解,不過又想到如果還有obj4、5、6就沒辦法了...而且objTotal不是CRUDModel了...窘
C# 不熟,不知道這樣行不行
objs.ForEach(e => {
foreach(PropertyInfo p in e.GetType().GetProperties())
{
objNew
.GetType()
.GetProperty(p.Name)
.SetValue(objNew, (bool)p.GetValue(objNew) || (bool)p.GetValue(e));
}
});
listennn08 可以!跟樓下思路相仿,感謝!
這就不限制你的屬性多少了
class Program
{
static void Main(string[] args)
{
var obj1 = new CRUDModel { Create = true };
var obj2 = new CRUDModel { Read = true };
var obj3 = new CRUDModel { Delete = true };
List<CRUDModel> CRUDModels = new List<CRUDModel> { obj1, obj2, obj3 };
CRUDModel res = new CRUDModel();
res = Test(CRUDModels);
}
public class CRUDModel
{
public bool Create { get; set; }
public bool Read { get; set; }
public bool Update { get; set; }
public bool Delete { get; set; }
}
public static CRUDModel Test(List<CRUDModel> CRUDModels)
{
CRUDModel res = new CRUDModel();
foreach (CRUDModel item in CRUDModels)
{
PropertyInfo[] propertyInfos = item.GetType().GetProperties();
foreach (PropertyInfo itemData in propertyInfos)
{
if (!(bool)res.GetType().GetProperty(itemData.Name).GetValue(res))
{
res.GetType().GetProperty(itemData.Name).SetValue(res, itemData.GetValue(item));
}
}
}
return res;
}
}