網(wǎng)站首頁 編程語言 正文
Linq利用Distinct去除重復(fù)項
添加一個擴(kuò)展方法
public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
? ? HashSet<TKey> seenKeys = new HashSet<TKey>();
? ? foreach (TSource element in source)
? ? {
? ? ? ? if (seenKeys.Add(keySelector(element)))
? ? ? ? {
? ? ? ? ? ? yield return element;
? ? ? ? }
? ? }
}
使用方法如下(針對ID,和Name進(jìn)行Distinct)
var query = people.DistinctBy(p => new { p.Id, p.Name });
若僅僅針對ID進(jìn)行distinct:
var query = people.DistinctBy(p => p.Id);
Linq利用Except去除重復(fù)數(shù)據(jù)并返回唯一數(shù)據(jù)(IEqualityComparer擴(kuò)展)
前段時間做一個項目就是定時下載節(jié)目列表進(jìn)行對文件時間和名字進(jìn)行新舊對比進(jìn)行去重復(fù),眾所周知,我們在Linq中去重復(fù)數(shù)據(jù)都用Distinct()做。
但如果想多個條件進(jìn)行對比去除重復(fù)數(shù)據(jù),我們應(yīng)該怎么辦呢?
請看下文,利用Except (通過使用默認(rèn)的相等比較器對值進(jìn)行比較,生成兩個序列的差集。)
//
// 摘要:
// 通過使用默認(rèn)的相等比較器對值進(jìn)行比較,生成兩個序列的差集。
//
// 參數(shù):
// first:
// System.Collections.Generic.IEnumerable`1 也不是在其元素 second 將返回。
//
// second:
// System.Collections.Generic.IEnumerable`1 同時出現(xiàn)在第一個序列的元素將導(dǎo)致從返回的序列中移除這些元素。
//
// 類型參數(shù):
// TSource:
// 輸入序列中的元素的類型。
//
// 返回結(jié)果:
// 包含這兩個序列的元素的差集的序列。
//
// 異常:
// T:System.ArgumentNullException:
// first 或 second 為 null。
public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
示例:
public class ChannelTvListInfo
{
public string TVName { get; set; } //節(jié)目列表名字
public string LastWriteTime { get; set; }//最后編輯文件時間
}
private List<ChannelTvListInfo> lstNewTvInfo, lstOldTvInfo = new List<ChannelTvListInfo>();
private void button3_Click(object sender, EventArgs e)
{ //通過下載后與定時下載的目錄文件進(jìn)行名字及最后編輯文件的時間進(jìn)行對比更新
lstNewTvInfo = listFTPFiles("60.208.140.xxx", "", "");
DirectoryInfo TheFolder = new DirectoryInfo(@"D:\ChannelTvXML\");
foreach (FileInfo NextFile in TheFolder.GetFileSystemInfos())
{
lstOldTvInfo.Add(new ChannelTvListInfo { TVName = NextFile.Name, LastWriteTime =
NextFile.LastWriteTime.ToString("yyyy/MM/dd hh:mm tt") });
}
}
public List<ChannelTvListInfo> listFTPFiles(string FTPAddress, string username, string password)
{
List<ChannelTvListInfo> listinfo = new List<ChannelTvListInfo>();
using (FtpConnection ftp = new FtpConnection(FTPAddress, username, password))
{
ftp.Open();
ftp.Login();
foreach (var file in ftp.GetFiles("/"))
{
listinfo.Add(new ChannelTvListInfo
{
TVName = file.Name,
LastWriteTime = Convert.ToDateTime(file.LastWriteTime).ToString("yyyy/MM/dd hh:mm tt")
});
}
ftp.Dispose();
ftp.Close();
}
return listinfo;
}
效果圖
1:自動從FTP目錄下載下來的xml 節(jié)目列表:
2:從上一個時間段自動下來的存放的目錄獲取文件列表
或者新舊List列表中的 差異節(jié)目列表方法:
var result = lstNewTvInfo.Except(lstOldTvInfo.Where(x=>x.TVName.Contains("四川")), new ProductComparer()).ToList();
以下示例顯示如何實(shí)現(xiàn)可在Distinct <TSource>方法中使用的等式比較器。
public class ProductComparer : IEqualityComparer<ChannelTvListInfo>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(ChannelTvListInfo x, ChannelTvListInfo y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.TVName == y.TVName && x.LastWriteTime == y.LastWriteTime;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(ChannelTvListInfo product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.TVName == null ? 0 : product.TVName.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.LastWriteTime.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
最終返回結(jié)果就是有差異的
總結(jié)
原文鏈接:https://blog.csdn.net/c1113072394/article/details/75330966
相關(guān)推薦
- 2023-01-18 pip?search報錯問題及解決_python
- 2023-01-15 React?18中的state概念與使用、注意問題解決_React
- 2022-10-27 樹莓派4B更換清華源和沒有公鑰報錯
- 2022-08-28 c++在windows、linux下獲取指定文件夾下所有文件名的方法
- 2022-03-16 .NET6導(dǎo)入和導(dǎo)出EXCEL_實(shí)用技巧
- 2022-10-03 利用正則表達(dá)式校驗金額最多保留兩位小數(shù)實(shí)例代碼_正則表達(dá)式
- 2023-01-14 C++?win系統(tǒng)如何用MinGW編譯Boost庫_C 語言
- 2022-03-20 Android四大組件之Activity詳細(xì)介紹_Android
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支