如何比较的X名单Y在C#中使用泛型列表? [英] How to compare list of X to list of Y in C# by using generics?

查看:243
本文介绍了如何比较的X名单Y在C#中使用泛型列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个班,X和Y这两个类具有相同的相似性如下图所示。

I have 2 classes, X and Y. Both classes have same similar property like below.

class X
{
    public string T1 { get; set; }
    public string T2 { get; set; }
    public string T3 { get; set; }
}

class Y
{
    public string T1 { get; set; }
    public string T2 { get; set; }
    public string T3 { get; set; }

    public string O1 { get; set; }
}

我有几个几百个类相似,X和Y;类似的结构,我决定为这个问题创建泛型类。

I've couple hundreds classes similar to X and Y; similar structure, and I decide to create generic class for this problem.

我有X和Y的名单,我想通过T1对它们进行比较;只有一间酒店,以找出哪些元素既列表,其中元素只存在于X和只在Y对存在。

I have list of X and Y and I want to compare them by T1; only 1 property, to find out which element exist on both list, which element exist only on X and only on Y.

我怎样才能做到这一点?

How can I do this?

推荐答案

做的最好的事情就是先创建一个包含 T1 只是一个接口。然后,你从这个接口继承各班像 X 。现在,基于该接口的,你可以轻松地创建泛型类或辅助类。

The best thing to do is to first create an interface that contains T1 only. Then you inherit each class like X and Y from this interface. Now you can easily create your generic classes or any helper classes based on this interface.

另外,你可以使用反射,或者如果您使用C#4.0中,可以使用动态。经典反射的方式来减缓对(大)列表,所以除非你缓存你的方法调用,你不应该采取这种做法。然而,C#4.0,通过DLR,这是足够快,在大多数情况下提供的方法缓存。

Alternatively, you may use reflection, or if you use C# 4.0, you can use dynamic. Classic reflection is way to slow for (large) lists, so unless you cache your method calls, you shouldn't take that approach. C# 4.0 however, provided method caching through the DLR, which is sufficiently fast in most cases.

或者(2):当你想这样做正确的,你想比较喜欢使用LINQ标准机制的列表,你应该实现IComparable。您可以combinee与泛型创建类型安全。

Alternatively (2): when you want to do this "right" and you want to compare the lists using standard mechanisms like LINQ, you should implement IComparable. You can combinee that with generics to create type-safety.

// the interface, inherit from IComparable
public interface IX : IComparable<IX>
{
    string T1 { get; set; }
}

// create one base class
class XBase : IX
{
    public string T1 { get; set; }
    public int CompareTo(IX obj)
    {
        return this.T1.equals(obj.T1);
    }
}

// inherit all others from base class
class X : XBase
{
    public string T2 { get; set; }
    public string T3 { get; set; }
}

class Y : XBase
{
    public string T2 { get; set; }
    public string T3 { get; set; }

    public strign O1 { get; set; }
}

有很多其他的方法。上述最后一个方法具有一次编写逻辑 T1 的CompareTo ,可节省杂波和创造的优势清晰度在code。

There are many other ways. The last method above has the advantage of only once writing the logic for T1 and CompareTo, which saves from clutter and creates clarity in your code.

这篇关于如何比较的X名单Y在C#中使用泛型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆