這是原本使用的動態Linq條件式使用Switch來達成不同的Where條件式
Func<JsonDataModel.RootObject, bool> isHeaderName;
switch (layer)
{
case Layer.MainCategory:
isHeaderName = (x) =>
{
return x.MainCategory == headerNameOnly;
};
break;
case Layer.SubCategory:
isHeaderName = (x) =>
{
return x.SubCategory == headerNameOnly;
};
break;
case Layer.SubSubCategory:
isHeaderName = (x) =>
{
return x.SubSubCategory == headerNameOnly;
};
break;
default:
thrownew NotImplementedException();
}
var item = JsonDataModel.jsonList.Where(isHeaderName)
.Select(x => new ListItemModel()
{
LineOne = x.Title,
LineTwo = x.Content,
Icon = string.Empty
});
----------------------------------------
// 以下為Linq的Where核心,使用反射來動態取得屬性然後組成Where的條件式
Func<JsonDataModel.RootObject, string, Layer, bool> isHeaderInLayer = (x, headerName, layer) =>
{
Type type = x.GetType();
PropertyInfo property = type.GetProperty(layer.ToString());
string category = (string)property.GetValue(x, null);
return category.Contains(headerName);
};
// 最後程式碼縮短很多,只需傳入參數就可以配合不同的需要,達成不同屬性裡是否包含指定的字串
var item = JsonDataModel.jsonList.Where(x => isHeaderInLayer(x, headerNameOnly, layer))
.Select(x => new ListItemModel()
{
LineOne = x.Title,
LineTwo = x.Content,
Icon = string.Empty
});