gpt4 book ai didi

c# - 使用 linq 从两个对象列表创建一个列表

转载 作者:IT王子 更新时间:2023-10-29 03:31:30 25 4
gpt4 key购买 nike

我有以下情况

class Person
{
string Name;
int Value;
int Change;
}

List<Person> list1;
List<Person> list2;

我需要将这两个列表组合成一个新的 List<Person>如果它是同一个人,则合并记录将具有该名称,即 list2 中此人的值,更改将是 list2 的值 - list1 的值。如果没有重复则变化为 0

最佳答案

这可以通过使用 Linq 扩展方法 Union 轻松完成。例如:

var mergedList = list1.Union(list2).ToList();

这将返回一个列表,其中两个列表合并并删除了 double 。如果您没有像我的示例那样在 Union 扩展方法中指定比较器,它将使用您的 Person 类中的默认 Equals 和 GetHashCode 方法。例如,如果你想通过比较他们的 Name 属性来比较人,你必须覆盖这些方法来自己执行比较。检查以下代码示例以完成该操作。您必须将此代码添加到您的 Person 类中。

/// <summary>
/// Checks if the provided object is equal to the current Person
/// </summary>
/// <param name="obj">Object to compare to the current Person</param>
/// <returns>True if equal, false if not</returns>
public override bool Equals(object obj)
{
// Try to cast the object to compare to to be a Person
var person = obj as Person;

return Equals(person);
}

/// <summary>
/// Returns an identifier for this instance
/// </summary>
public override int GetHashCode()
{
return Name.GetHashCode();
}

/// <summary>
/// Checks if the provided Person is equal to the current Person
/// </summary>
/// <param name="personToCompareTo">Person to compare to the current person</param>
/// <returns>True if equal, false if not</returns>
public bool Equals(Person personToCompareTo)
{
// Check if person is being compared to a non person. In that case always return false.
if (personToCompareTo == null) return false;

// If the person to compare to does not have a Name assigned yet, we can't define if it's the same. Return false.
if (string.IsNullOrEmpty(personToCompareTo.Name) return false;

// Check if both person objects contain the same Name. In that case they're assumed equal.
return Name.Equals(personToCompareTo.Name);
}

如果您不想将 Person 类的默认 Equals 方法设置为始终使用 Name 来比较两个对象,您还可以编写一个使用 IEqualityComparer 接口(interface)的比较器类。然后,您可以提供此比较器作为 Linq 扩展 Union 方法中的第二个参数。有关如何编写此类比较器方法的更多信息,请参见 http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx

关于c# - 使用 linq 从两个对象列表创建一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/720609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com