关于交集(Intersect)和差集(Except)

函数经常会用到关于运算方面的东西。有时复杂的逻辑会变得更加容易理解。

在C#3.0,可以有几个方法推荐用用。实际场景如下:

代码
        /// <summary>
        
/// 控制图片删除或增加
        
/// </summary>
        
/// <param name="_uploadImagesCtrl">上传控件</param>
        
/// <param name="templist">输出差集,用于新增</param>
        
/// <param name="temptradelist">输出差集,用于删除</param>
        
/// <param name="nowlist">现在的图片集合</param>
        
/// <param name="oldPictureList">原始的图片集合</param>
        private static void ControlImagesDeleteOrAdd(FxUploadImage _uploadImagesCtrl,
            
out IList<string> templist, out IList<string> temptradelist,
            IList
<string> nowlist, IList<string> oldPictureList)
        {
            
// 现在元素和原始数据的交集
            IList<string> temp = ((from c in nowlist select c).Intersect(from b in oldPictureList select b)).ToList();


            
//与非 返回2个集合多余的元素||这个是新增
            templist = ((from c in nowlist select c).Except(from b in temp select b)).ToList();
            
//与非 返回2个集合多余的元素||这个是删除
            temptradelist = ((from c in oldPictureList select c).Except(from b in temp select b)).ToList();
        }

代码的零碎片段。这2个函数,应该是LINQ的方法Intersect(交集),Except(差集)

假设 Intersect,为分界。前面是第一集合,后面是第二集合。Except也一样。

Intersect是第一个集合 交 第二个集合。公共的部分。

Except是第一集合 交 第二个集合,返回的是 第一个集合在第二集合没有的部分(差集)。

PS:Except补充说明,记得有的文章和评论说反了呢。这里具体例子我都验证过了。返回的一定是第一集合多余出来的部分,而不是第二集合的。

适用范围:只有First,end的逻辑,中间复杂的东西不管,也有可能管不来。就可以用交集,差集来计算了。当然,多做点,多思考点。然后方法自然有的。

原文地址:https://www.cnblogs.com/drek_blog/p/1657141.html