简体   繁体   English

如何区分()列出包含实现接口的类的列表? C#

[英]How to Distinct() List which contains classes that implement interface? C#

First of all, I have interfact ICommand : 首先,我有完整的ICommand

public interface ICommand
{
}

and concrete classes ThreadSelectCommand , SearchCommand and so on: 以及具体的类ThreadSelectCommandSearchCommand等:

public class ThreadSelectCommand : ICommand
{
    public int Value { get; set; }

    public ThreadSelectCommand()
    {
        Value = 1;
    }
}


public class SearchCommand : ICommand
{
    public string Value { get; set; }
    public SearchCommand()
    {
        Value = "";
    }
}

List<ICommand> resultCommands can contains a few of each command, and I need to Distinct() this list. List<ICommand> resultCommands可以包含每个命令中的一些命令,我​​需要Distinct()此列表。 How to do this? 这个怎么做? I know, that I should use comparator. 我知道,我应该使用比较器。 But this classes are not the same. 但是这个类是不一样的。

The requirements you want (only one instance per concrete type) can be done by comparing the runtime types of the elements in the list. 您可以通过比较列表中元素的运行时类型来完成所需的要求(每种具体类型仅一个实例)。

public class  CommandTypeComparer : EqualityComparer<ICommand> 
{
    public override bool Equals(ICommand x, ICommand y)
    {
        return Type.Equals(x.GetType(), y.GetType());
    }

    public override int GetHashCode(ICommand x)
    {
        return x.GetType().GetHashCode()
    }
}

You would then use it like resultCommands.Distinct(new CommandTypeComparer()); 然后,您可以像resultCommands.Distinct(new CommandTypeComparer());一样使用它resultCommands.Distinct(new CommandTypeComparer());

Assume that you have a following list of object as your sample above 假设您具有以下对象列表作为上面的示例

List<ICommand> resultCommands = new List<ICommand> {
    new ThreadSelectCommand(),
    new ThreadSelectCommand(),
    new ThreadSelectCommand(),
    new SearchCommand(),
    new SearchCommand(),
};  


var groups = resultCommands.GroupBy(x => x.GetType());

var distinctList = groups.Select(g => { 
    if(g.Key == typeof(ThreadSelectCommand))
    {
        return g.Select(x => (ThreadSelectCommand)x).GroupBy(x => new { x.Value }).Select(x => (ICommand)x.First()).First();
    }
    else if(g.Key == typeof(SearchCommand))
    {
        return g.Select(x => (SearchCommand)x).GroupBy(x => new { x.Value }).Select(x => (ICommand)x.First()).First();
    }
    else 
    {
        throw new NotSupportedException();
    }

    }).ToList();

The distinctList will contain 2 elements distanceList将包含2个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM