C#split按实现划分的接口列表

AsV*_*leO 6 c# implementation split interface list

我需要拆分List<IInterface>以获取具体实现的列表IInterface.我怎样才能以最佳方式做到这一点?

        public interface IPet { }
        public class Dog :IPet { }
        public class Cat : IPet { }
        public class Parrot : IPet { }

        public void Act()
        {
            var lst = new List<IPet>() {new Dog(),new Cat(),new Parrot()};
            // I need to get three lists that hold each implementation 
            // of IPet: List<Dog>, List<Cat>, List<Parrot>
        }
Run Code Online (Sandbox Code Playgroud)

Nic*_*ico 11

你可以GroupBy按类型做:

var grouped = lst.GroupBy(i => i.GetType()).Select(g => g.ToList()).ToList()
Run Code Online (Sandbox Code Playgroud)

如果你想要一个字典,你可以这样做:

var grouped = lst.GroupBy(i => i.GetType()).ToDictionary(g => g.Key, g => g.ToList());
var dogList = grouped[typeof(Dog)];
Run Code Online (Sandbox Code Playgroud)

或者蒂姆在评论中提出:

var grouped = lst.ToLookup(i => i.GetType());
Run Code Online (Sandbox Code Playgroud)

  • 很好,你甚至不需要提前了解所有类型 (2认同)
  • 这可以在第二种情况下优化为var grouped = lst.ToLookup(x => x.GetType()); (2认同)