c# - 从两个列表中过滤掉重复项,如果重复则更改对象属性值
问题描述
我有两个列表 AuthorList 和 AuthorList2。目前我正在使用带有简单 IEqualityComparer 类的联合。我希望有一个没有来自 AuthorList 和 AuthorList2 的重复项的结果列表,如果这些列表中有任何重复项,则需要将它们从列表中删除,并且需要将重复项的 Author 类 Assigned 属性设置为 true。
来自两个 AuthorLists 的现有信息:
产品 ID 和分配
- 1、假的
- 2、假的
- 3、假的
- 1、假的
结果列表:
产品 ID 和分配
- 1、真
- 2、假的
- 3、假的
逻辑需要过滤掉重复项,如果这两个列表具有相同的元素,则更改false -> true。
namespace HelloWorld
{
class Hello
{
static void Main()
{
List<Author> AuthorList = new List<Author>
{
new Author(1, false),
new Author(2, false),
new Author(3, false)
};
List<Author> AuthorList2 = new List<Author>
{
new Author(1, false)
};
var compareById = new AuthorComparer(false);
var result = AuthorList.Union(AuthorList2, compareById);
foreach (var item in result)
{
Console.WriteLine("Result: {0},{1}", item.ProductId, item.Assigned);
}
Console.ReadKey();
}
public class AuthorComparer : IEqualityComparer<Author>
{
private bool m_withValue;
public AuthorComparer(bool withValue)
{
m_withValue = withValue;
}
public bool Equals(Author x, Author y)
{
return (x.ProductId == y.ProductId);
}
public int GetHashCode(Author x)
{
return x.ProductId.GetHashCode();
}
}
public class Author
{
private int productId;
private bool assigned;
public Author(int productId, bool assigned)
{
this.productId = productId;
this.assigned = assigned;
}
public int ProductId
{
get { return productId; }
set { productId = value; }
}
public bool Assigned
{
get { return assigned; }
set { assigned = value; }
}
}
}
}
解决方案
您正在寻找的代码是这样的:
AuthorList.ForEach(a => a.Assigned = AuthorList2.Exists(b => b.ProductId == a.ProductId));
你根本不需要IEqualityComparer
。
完整的工作代码:
namespace HelloWorld
{
class Hello
{
static void Main()
{
List<Author> AuthorList = new List<Author>
{
new Author(1, false),
new Author(2, false),
new Author(3, false)
};
List<Author> AuthorList2 = new List<Author>
{
new Author(1, false)
};
AuthorList.ForEach(a => a.Assigned = AuthorList2.Exists(b => b.ProductId == a.ProductId));
foreach (var item in AuthorList)
{
Console.WriteLine("Result: {0},{1}", item.ProductId, item.Assigned);
}
Console.ReadKey();
}
public class Author
{
public Author(int productId, bool assigned)
{
this.ProductId = productId;
this.Assigned = assigned;
}
public int ProductId { get; set; }
public bool Assigned { get; set; }
}
}
}
推荐阅读
- python - 使用python在qt中显示原始图像
- asp.net - Gridview 从数据库时间戳中删除毫秒
- vue.js - @click 不会触发 vue.js 的标题链接
- c# - 文件名中的 aspnet-user-identity,但它并不总是有效
- c++ - 为什么元组中的变量类型不匹配,而函数中的变量类型不匹配?
- python - 如何对多个变量和多个模型执行(修改)t 检验
- jquery - 验证表单窗口打开
- swift - Swift“有望解码 Array
而是找到了一本字典。” - ruby-on-rails - Capybara selenium_chrome 去 example.com 而不是 localhost
- python - 在 Python 2.7 中使用列中的数据解析示例工作表文件