You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从两个列表去重,重复时修改Author对象Assigned属性值

刚好做过类似的需求!你要的是合并两个Author列表时,不仅去重,还要把那些在两个列表里都出现过的元素的Assigned属性改成true,对吧?Union本身只能帮你去重,但不会自动修改属性,所以得结合自定义比较器再加一步处理,我给你捋清楚怎么做:

第一步:先明确Author类和自定义比较器

首先得确保你的Author类结构正确,然后写一个按ProductID判断元素是否重复的比较器——因为你的重复判断依据是ProductID相同:

public class Author
{
    public int ProductID { get; set; }
    public bool Assigned { get; set; }

    // 可选:重写ToString方便调试输出
    public override string ToString()
    {
        return $"{ProductID}, {Assigned}";
    }
}

public class AuthorEqualityComparer : IEqualityComparer<Author>
{
    public bool Equals(Author x, Author y)
    {
        if (x == null || y == null) return false;
        // 只按ProductID判断是否为重复元素
        return x.ProductID == y.ProductID;
    }

    public int GetHashCode(Author obj)
    {
        // 用ProductID的哈希值作为比较依据
        return obj.ProductID.GetHashCode();
    }
}

第二步:实现去重+修改重复元素属性的逻辑

直接用Union只能得到去重后的列表,但没法修改属性,所以我们需要先找出重复的ProductID,再在合并时给对应元素设置Assigned = true:

// 模拟你的原始列表
var AuthorList = new List<Author>
{
    new Author { ProductID = 1, Assigned = false },
    new Author { ProductID = 2, Assigned = false },
    new Author { ProductID = 3, Assigned = false }
};

var AuthorList2 = new List<Author>
{
    new Author { ProductID = 1, Assigned = false }
};

var comparer = new AuthorEqualityComparer();

// 1. 先找出两个列表中重复的ProductID(用HashSet提升查找效率)
var duplicateProductIds = AuthorList.Intersect(AuthorList2, comparer)
                                   .Select(a => a.ProductID)
                                   .ToHashSet();

// 2. 合并去重,同时给重复元素设置Assigned=true
var result = AuthorList.Union(AuthorList2, comparer)
                       .Select(a => new Author 
                       { 
                           ProductID = a.ProductID, 
                           Assigned = duplicateProductIds.Contains(a.ProductID) 
                       })
                       .ToList();

// 验证结果(输出:1,True;2,False;3,False)
foreach (var item in result)
{
    Console.WriteLine(item);
}

如果你不想创建新的Author对象,而是直接修改原列表中的元素引用,可以换下面的写法:

// 先获取去重后的所有元素
var uniqueAuthors = AuthorList.Union(AuthorList2, comparer).ToList();

// 找出重复的ProductID
var duplicateIds = AuthorList.Select(a => a.ProductID)
                            .Intersect(AuthorList2.Select(a => a.ProductID))
                            .ToHashSet();

// 遍历修改属性
foreach (var author in uniqueAuthors)
{
    if (duplicateIds.Contains(author.ProductID))
    {
        author.Assigned = true;
    }
}

这个逻辑完全符合你的预期:去重后,重复出现的元素Assigned设为true,其余保持false。

内容的提问来源于stack exchange,提问作者kerpekri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:55:12