gpt4 book ai didi

c# - 您如何将与集合中其他项目具有依赖性的项目分组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:53 27 4
gpt4 key购买 nike

我需要找到一个漂亮、干净的方法来获得 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" }) { }
}

本质上,我想要实现的目标是这样的:

Amount => CustomerDate, AppointmentDate, SomethingElse
CustomerDate => Amount, AppointmentDate
AppointmentDate => Amount, CustomerDate, SomethingElse
SomethingElse => Amount, AppointmentDate, Something
Something => SomethingElse

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

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

最佳答案

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

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();

输出:

Amount => CustomerDate, AppointmentDate, SomethingElse
CustomerDate => Amount, AppointmentDate
AppointmentDate => Amount, CustomerDate, SomethingElse
SomethingElse => Amount, AppointmentDate, Something
Something => SomethingElse

关于c# - 您如何将与集合中其他项目具有依赖性的项目分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21391594/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com