我正在嘗試根據每個列舉選項的屬性來查詢我的列舉。
我知道如何獲取串列。通過這段代碼很簡單:
var list = Enum.GetValues(typeof(FamilyNameOptions))
.Cast<FamilyNameOptions>()
.Select(v => v.ToString())
.ToList();
如果這是我的列舉設定,我如何查詢值為TRUE的屬性DrawingListIsEnabled
public enum FamilyNameOptions
{
[DrawingListIsEnabled(true)]
[FamilyUserName("FamilyName1")]
FamilyName1= 0,
[DrawingListIsEnabled(false)]
[FamilyUserName("FamilyName2")]
FamilyName2= 1,
}
/// <summary>
/// DrawingListIsEnabledAttribute
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.All)]
public class DrawingListIsEnabledAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DrawingListIsEnabledAttribute"/> class.
/// </summary>
/// <param name="isEnabled">if set to <c>true</c> [is enabled].</param>
public DrawingListIsEnabledAttribute(bool isEnabled)
{
this.IsEnabled = isEnabled;
}
/// <summary>
/// Gets a value indicating whether this instance is enabled.
/// </summary>
/// <value>
/// <c>true</c> if this instance is enabled; otherwise, <c>false</c>.
/// </value>
public bool IsEnabled { get; private set; }
}
預期的結果將是 1 的串列:
姓氏1
uj5u.com熱心網友回復:
而不是使用Enum.GetValues您將需要使用反射來查找靜態欄位串列;
typeof(FamilyNameOptions)
.GetFields(BindingFlags.Static | BindingFlags.Public)
// For definition order, rather than value order;
.OrderBy(f => f.MetadataToken)
.Select(f => new {
Value = (FamilyNameOptions)f.GetValue(null),
Text = f.Name,
Enabled = f.GetCustomAttribute<DrawingListIsEnabledAttribute>()?.IsEnabled ?? false,
FamilyName = f.GetCustomAttribute<FamilyUserNameAttribute>()?.Name
})
由于這些資訊在運行時都不會更改,因此您可能希望創建一個輔助型別來快取結果。
uj5u.com熱心網友回復:
這是完成此任務的簡單 LINQ 查詢:
var items = Enum.GetValues<FamilyNameOptions>()
.Select(item => item.GetType().GetMember(item.ToString()).FirstOrDefault())
.Where(memberInfo => memberInfo?.GetCustomAttribute<DrawingListIsEnabledAttribute>().IsEnabled ?? false)
.Select(enabledMemberInfo => enabledMemberInfo.GetCustomAttribute<FamilyUserNameAttribute>().FamilyUserName);
請注意,您不需要原始list. 另外,我使用的是 的通用版本Enum.GetValues<TEnum>,這消除了Cast您的版本中的需要。
我長時間保留我的 LINQ 名稱,以便進行自我記錄;隨意使用典型的較短名稱。該代碼的作業原理如下:
Enum.GetValues<FamilyNameOptions>回傳 的成員的強型別串列enum FamilyNameOptions。- 第一
.Select條陳述句獲取MemberInfo描述列舉成員的物件(以及所有自定義屬性) - 接下來,
.Where根據DrawingListIsEnabledAttribute的IsEnabled屬性過濾結果 - 最后,最后一個
.Select從FamilyUserNameAttribute'FamilyUserName屬性中獲取名稱(我想這就是它的名稱 - 如果不是,請相應地更改它)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431540.html
上一篇:使用linqC#更新串列
