您可以使用Linq
的Except
擴展方法:
holidayDifference = remoteHolidays
.Except(localHolidays)
.ToList();
注意,這將還需要Holiday
實施有效的Equals method of IEquatable<Holiday>
方法o verride,也GetHashCode
必須返回一個相同的散列兩個Holidays
其中Equals
返回true
。
此外,Except
是返回(在這種情況下)的IEnumerable<Holiday>
因此你將不得不使用ToList
擴展方法,以檢索List<Holiday>
備選地延伸,則可以使用other overload of Except
它允許你提供一個IEqualityComparer<Holiday>
而不是修改您的原始類。
與strings
實施例:
List<string> holidayDifference = new List<string>();
List<string> remoteHolidays = new List<string> { "1", "2", "3" };
List<string> localHolidays = new List<string> { "1", "3" };
holidayDifference = remoteHolidays
.Except(localHolidays)
.ToList();
holidayDifference.ForEach(Console.WriteLine);
輸出:
實施例隨着Holiday : IEquatable<Holiday>
:
class Holiday : IEquatable<Holiday>
{
public string Name { get; set; }
public bool Equals(Holiday other)
{
return Name == other.Name;
}
// GetHashCode must return true whenever Equals returns true.
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
return Name?.GetHashCode() ?? 0;
}
}
public class Program
{
public static void Main()
{
List<Holiday> holidayDifference = new List<Holiday>();
List<Holiday> remoteHolidays = new List<Holiday>
{
new Holiday { Name = "Xmas" },
new Holiday { Name = "Hanukkah" },
new Holiday { Name = "Ramadan" }
};
List<Holiday> localHolidays = new List<Holiday>
{
new Holiday { Name = "Xmas" },
new Holiday { Name = "Ramadan" }
};
holidayDifference = remoteHolidays
.Except(localHolidays)
.ToList();
holidayDifference.ForEach(x => Console.WriteLine(x.Name));
}
}
輸出:
光明
爲什麼要求'foreach'循環? – Aphelion
可能的重複http://stackoverflow.com/questions/806152/is-there-a-way-to-get-the-difference-between-two-sets-of-objects-in-c-sharp? –