【发布时间】:2018-05-10 10:20:44
【问题描述】:
我有两个列表 AuthorList 和 AuthorList2。目前我正在使用带有简单 IEqualityComparer 类的联合。 我希望有一个没有来自 AuthorList 和 AuthorList2 的重复项的结果列表,如果这些列表中有任何重复项,则需要将它们从列表中删除,并且需要将重复项的 Author 类 Assigned 属性设置为 true。
来自两个 AuthorLists 的现有信息:
ProductID 和分配
- 1,假
- 2,错误
- 3,错误
- 1,假
结果列表:
ProductID 和分配
- 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或AuthorList2的元素吗?我怀疑一个简单的Intersect电话在这里会有所帮助,但目前尚不清楚您期望什么结果...... -
我正在尝试更新/过滤 AuthorList 的元素。我希望有一个没有任何重复项的列表,如果列表中有任何重复项,则需要将它们从列表中删除,并且 Author 类的 Assigned 属性需要设置为 true。
-
顺便说一句,如果您使用自动实现的属性,您的
Author类可能会简单得多:public int ProductId { get; set; } public bool Assigned { get; set; }- 并放弃字段。