C# 自定義實體(類)List 復雜實體(類)List 的 Compare, 是否包含(Contains()),去重( Distinct())


對於簡單數據類型的List,檢查是否包含某個值,或去重可以直接使用List的方法Contains()或Distinct()。

但是對於 自定義實體(類)的List 進行是否包含實體(Contains)的檢查,或者去重(Distinct)操作時,直接使用Contains()或Distinct()方法是不能達到效果的。

此時需要我們定義一個專門處理當前自定義實體(類)的這些操作的一個類。為了方便起見,一般將這兩個類(自定義的實體(類),處理這個自定義類的類) 放在一起(當然完全可以不放在一起,只要自己方便查找、管理即可)。

示例代碼:

實體:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace BusinessInvestment
{
    /// <summary>
    /// 自定義實體
    /// </summary>
    public class ContractProjIndustryTotalInvestDto
    {
        /// <summary>
        ///  行業
        /// </summary>                
        public string Industry { get; set; }       

        /// <summary>
        ///  行業名稱
        /// </summary>        
        public string IndustryName { get; set; }

        /// <summary>
        ///  總投資
        /// </summary>        
        public decimal? TotalInvest { get; set; }
        
    }  

  //用來處理 ContractProjIndustryTotalInvestDto 類的類,需要繼承 IEqualityComparer接口,這個接口需要引用 System.Collections.Generic 命名空間
    public class ContractProjIndustryTotalInvestDtoComparer : IEqualityComparer<ContractProjIndustryTotalInvestDto>
    {
        public bool Equals(ContractProjIndustryTotalInvestDto x, ContractProjIndustryTotalInvestDto y)
        {
            if (x == null || y == null)
                return false;
            if (x.Industry == y.Industry && x.IndustryName==y.IndustryName)//自定義的比較的方法,這里就是核心了
                return true;
            else
                return false;
        }

        public int GetHashCode(ContractProjIndustryTotalInvestDto obj)
        {
            if (obj == null)
                return 0;
            else
                return obj.IndustryName.GetHashCode();
        }
    }
}

應用:

/* 省略部分代碼 */
// originalDataList 為原始數據
List<ContractProjIndustryTotalInvestDto> tempDataList = new List<ContractProjIndustryTotalInvestDto>();
for (int i = 0; i < originalDataList.Count; i++)
{
    var currentTempData = originalDataList[i];
    //判斷 tempDataList 列表是否包含當前循環的實體(Contains())
    var isContains=tempDataList.Contains(currentTempData,new ContractProjIndustryTotalInvestDtoComparer());
    if (!isContains)
    {
        /* 省略部分代碼 */
        tempDataList.Add(currentTempData);                
        /* 省略部分代碼 */
    }
}
//對 tempDataList 列表去重(Distinct())
var retData = tempDataList.Distinct(new ContractProjIndustryTotalInvestDtoComparer()).ToList();
/* 省略部分代碼 */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM