Tôi đang sử dụng phương thức Enumerable.Union<TSource>
để lấy liên kết của Danh sách tùy chỉnh1 với Danh sách tùy chỉnh2. Nhưng bằng cách nào đó nó không hoạt động như trong trường hợp của tôi. Tôi nhận được tất cả các mục cũng trùng lặp một lần.Cách sử dụng C# LINQ Union để nhận Liên minh Danh sách tùy chỉnh1 với danh sách2
Tôi theo dõi MSDN Link để hoàn thành công việc, nhưng tôi vẫn không thể đạt được điều tương tự.
Tiếp theo là Bộ luật của lớp tùy chỉnh: -
public class CustomFormat : IEqualityComparer<CustomFormat>
{
private string mask;
public string Mask
{
get { return mask; }
set { mask = value; }
}
private int type;//0 for Default 1 for userdefined
public int Type
{
get { return type; }
set { type = value; }
}
public CustomFormat(string c_maskin, int c_type)
{
mask = c_maskin;
type = c_type;
}
public bool Equals(CustomFormat x, CustomFormat y)
{
if (ReferenceEquals(x, y)) return true;
//Check whether the products' properties are equal.
return x != null && y != null && x.Mask.Equals(y.Mask) && x.Type.Equals(y.Type);
}
public int GetHashCode(CustomFormat obj)
{
//Get hash code for the Name field if it is not null.
int hashProductName = obj.Mask == null ? 0 : obj.Mask.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = obj.Type.GetHashCode();
//Calculate the hash code for the product.
return hashProductName^hashProductCode;
}
}
này tôi kêu gọi như sau: -
List<CustomFormat> l1 = new List<CustomFormat>();
l1.Add(new CustomFormat("#",1));
l1.Add(new CustomFormat("##",1));
l1.Add(new CustomFormat("###",1));
l1.Add(new CustomFormat("####",1));
List<CustomFormat> l2 = new List<CustomFormat>();
l2.Add(new CustomFormat("#",1));
l2.Add(new CustomFormat("##",1));
l2.Add(new CustomFormat("###",1));
l2.Add(new CustomFormat("####",1));
l2.Add(new CustomFormat("## ###.0",1));
l1 = l1.Union(l2).ToList();
foreach(var l3 in l1)
{
Console.WriteLine(l3.Mask + " " + l3.Type);
}
Xin gợi ý cách thích hợp để đạt được cùng!
Có vẻ lạ, nhưng mã của bạn hoạt động nếu bạn a) cung cấp một hàm tạo parameterless cho CustomFormat và chuyển một thể hiện của lớp đó sang phương thức Union - xem https://dotnetfiddle.net/YTVwTI. Câu hỏi sau đó là tại sao Union bỏ qua việc thực hiện IEqualityComparer trong lớp. –
stuartd