日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Linq利用Distinct去除重復項問題(可自己指定)_C#教程

作者:MrCui. ? 更新時間: 2023-03-20 編程語言

Linq利用Distinct去除重復項

添加一個擴展方法

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進行Distinct)

var query = people.DistinctBy(p => new { p.Id, p.Name });

若僅僅針對ID進行distinct:

var query = people.DistinctBy(p => p.Id);

Linq利用Except去除重復數據并返回唯一數據(IEqualityComparer擴展)

前段時間做一個項目就是定時下載節目列表進行對文件時間和名字進行新舊對比進行去重復,眾所周知,我們在Linq中去重復數據都用Distinct()做。

但如果想多個條件進行對比去除重復數據,我們應該怎么辦呢?

請看下文,利用Except (通過使用默認的相等比較器對值進行比較,生成兩個序列的差集。)

  //
        // 摘要:
        //     通過使用默認的相等比較器對值進行比較,生成兩個序列的差集。
        //
        // 參數:
        //   first:
        //     System.Collections.Generic.IEnumerable`1 也不是在其元素 second 將返回。
        //
        //   second:
        //     System.Collections.Generic.IEnumerable`1 同時出現在第一個序列的元素將導致從返回的序列中移除這些元素。
        //
        // 類型參數:
        //   TSource:
        //     輸入序列中的元素的類型。
        //
        // 返回結果:
        //     包含這兩個序列的元素的差集的序列。
        //
        // 異常:
        //   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; } //節目列表名字
        public string LastWriteTime { get; set; }//最后編輯文件時間
    }
private List<ChannelTvListInfo> lstNewTvInfo, lstOldTvInfo = new List<ChannelTvListInfo>();
		private void button3_Click(object sender, EventArgs e)
		{       //通過下載后與定時下載的目錄文件進行名字及最后編輯文件的時間進行對比更新
			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 節目列表:

2:從上一個時間段自動下來的存放的目錄獲取文件列表

或者新舊List列表中的 差異節目列表方法:

var result = lstNewTvInfo.Except(lstOldTvInfo.Where(x=>x.TVName.Contains("四川")), new ProductComparer()).ToList();

以下示例顯示如何實現可在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;
		}
 
	}

最終返回結果就是有差異的

總結

原文鏈接:https://blog.csdn.net/c1113072394/article/details/75330966

欄目分類
最近更新