如何将具有依赖关系的项目组合到集合中的其他项目?

时间:2014-01-27 21:02:44

标签: c# algorithm linq dictionary enumeration

我需要找到一个很好,干净的方法来获取IDictionary<string, ICollection<string>>字段及其相关的依赖项。确定的方法是通过一堆集合,寻找该集合中的字段,然后找到所有不同的依赖项。示例代码:

public interface IFoo
{
    ICollection<string> Dependencies { get; }
}

public abstract class Foo<T> : IFoo
{
    protected Foo(ICollection<string> dependencies)
    {
        Dependencies = dependencies;
    }

    public ICollection<string> Dependencies { get; private set; }
}

public class FooA1 : Foo<A>
{
    public FooA1()
        :base(new Collection<string>() { "Amount", "CustomerDate", "AppointmentDate" }) { }
 }

public class FooA2 : Foo<A>
{
    public FooA2()
        :base(new Collection<string>() { "Amount", "AppointmentDate", "SomethingElse" }) { }
 }

public class FooA3 : Foo<A>
{
    public FooA3()
        :base(new Collection<string>() { "SomethingElse", "Something" }) { }
}

基本上,我想要实现的目标如下:

  

金额=&gt; CustomerDate,AppointmentDate,SomethingElse
  CustomerDate =&gt;金额,任命日期
  AppointmentDate =&gt;金额,CustomerDate,SomethingElse
  SomethingElse =&gt;金额,约会日期,东西
  某事=&gt; SomethingElse

现在,我知道如何获取所有字段的列表(假设我已经列出了所有实例):instances.SelectMany(i => i.Dependencies).Distinct();

问题是,如何以一种干净的方式获取该字段上所有依赖项的列表(最好使用LINQ)。

1 个答案:

答案 0 :(得分:2)

这会输出您要求的内容。这是我想出的第一件事,可能会在某处进行优化。

var nice = instances.SelectMany(instance => instance.Dependencies)
    .Distinct()
    .Select(dependency => new { d = dependency, o = instances.Where(instance => instance.Dependencies.Contains(dependency)).SelectMany(instance => instance.Dependencies).Except(new string[] { dependency }).Distinct() })
    .Select(a => a.d + " => " + string.Join(", ", a.o));

// If you're in LINQPad
nice.Dump();

输出:

  

金额=&gt; CustomerDate,AppointmentDate,SomethingElse
  CustomerDate =&gt;金额,任命日期
  AppointmentDate =&gt;金额,CustomerDate,SomethingElse
  SomethingElse =&gt;金额,约会日期,东西
  某事=&gt; SomethingElse