簡體   English   中英

比較兩個具有布爾屬性的通用項目,如果其中任何一個為true,則返回true,如結果通用列表中所示

[英]Compare two generic items which has boolean properties, if any of them true returns true as in result generic list

我正在嘗試比較兩個具有相同屬性的通用項。 如果要比較的屬性,則在列表項的任何一項中為true表示返回TRUE否則為FALSE因為我是c#的新手,因此無法在此處發布對不起的代碼。 項目1和項目2具有相同的屬性,但根據不同情況進行計算:需要檢查布爾屬性。

public class RrmModulePermission : BaseEntity
    {

        public long Id { get; set; }
        public int? EmployeeId { get; set; }
        public int? DesignationId { get; set; }
        public int ModuleId { get; set; }
        public bool View { get; set; }
        public bool ViewAll { get; set; }
        public bool Add { get; set; }
        public bool Edit { get; set; }
        public bool Delete { get; set; }
        public bool Import { get; set; }
        public bool Export { get; set; }
        public int CreatedBy { get; set; }
        public DateTimeOffset CreatedOn { get; set; }
        public int? UpdatedBy { get; set; }
        public DateTimeOffset? UpdatedOn { get; set; }
        public virtual RrmModule Modules { get; set; }

    }


 var list3 = new RrmModulePermission();
            if (list1.View || list2.View)
            {
                list3.View = true;
            }
            if (list1.Add || list2.Add)
            {
                list3.Add = true;
            }
            if (list1.Edit || list2.Edit)
            {
                list3.Edit = true;
            }
            if(list1.Delete || list2.Delete)
            {
                list3.Delete = true;
            }
            return list3;

從您呈現代碼的方式來看,我建議像這樣初始化list3

// if both are null, return an object with all bools as false
if (list1 == null && list2 == null)
    return new RrmModulePermission();

// if list1 is null, set all bools to false
if (list1 == null)
    list1 = new RrmModulePermission();

// if list2 is null, set all bools to false
if (list2 == null)
    list2 = new RrmModulePermission();

var list3 = new RrmModulePermission
{
    View = list1.View || list2.View,
    ViewAll = list1.ViewAll || list2.ViewAll,
    Add = list1.Add || list2.Add,
    Edit = list1.Edit || list2.Edit,
    Delete = list1.Delete || list2.Delete,
    Import = list1.Import || list2.Import,
    Export = list1.Export || list2.Export
};

return list3;

請注意,如果您將任何屬性的默認值設置為 true ,則需要替換

new RrmModulePermission();

與(您只需更改默認值為 true 的屬性

new RrmModulePermission
{
    View = false,
    ViewAll = false,
    Add = false,
    Edit = false,
    Delete = false,
    Import = false,
    Export = false
};

例如,如果僅“ Add 默認設置為 true 使用

new RrmModulePermission { Add = false };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM