使用來自枚舉的反射來從id獲取名稱。我使用的是:如何在C#中使用Linq和Reflection?
foreach(string idValue in Values)
{
var listSource = itemsSource as IEnumerable;
Type listType = listSource.GetType().GenericTypeArguments[0]
PropertyInfo idProperty = listType.GetType().GetProperty("Id");
PropertyInfo nameProperty = listType.GetType().GetProperty("Name");
foreach (var listItem in listSource)
{
if (idValue.Equals(idProperty.GetValue(listItem, null).ToString()))
{
value = nameProperty.GetValue(listItem, null).ToString();
break;
}
}
//do something with value.
}
如何使用Linq與反思,讓我不必通過在外環「idValue」的每個值元素循環?
類似:
reflectionList.Select(x=> x.idProperty == idValue)
,並用它來獲取nameProperty
請幫助值。
使用LINQ不會避免循環,它只是意味着你不需要寫出它們。 – Servy
將使用添加到System.Linq? – Botonomous
你的問題是什麼? _「如何將其轉換爲Linq」_? – CodeCaster