所以我有个学术问题。我能够用蛮力的方法解决这个问题,但我相信它在LINQ中是可以更优雅地解决的--然而,我无法找到这样做的方法。解决方案可以是C#或VB,是LINQ本身给我带来了麻烦。
我的目标如下:
public class Foo
{
public int FooId {get; set; }
public int Bar {get; set; }
/// <summary>
/// Contains list of FooId
/// </summary>
public int[] Stackability
}我需要做的是根据Foo的Stackability (即:可堆栈列表中的公共FooId )查找所有可能的分组,然后选择Bar之和最高的分组。
因此,例如:我有Ids为1、2和3的Foos。
+-------+-----+--------------+
| FooId | Bar | Stackability |
+-------+-----+--------------+
| 1 | 5 | 2, 3 |
+-------+-----+--------------+
| 2 | 2 | 1, 3 |
+-------+-----+--------------+
| 3 | 6 | 1 |
+-------+-----+--------------+ 在本例中,Foo 1可以与Foo 2和Foo 3堆栈,Foo 2可以与Foo 1和Foo 3堆栈,Foo 3只能与Foo 1堆栈。
注意,堆叠必须是相互的(因此,即使Foo 2可以与Foo 1和Foo 3堆栈,Foo 3只能与Foo 1堆栈,这意味着Foo 2实际上只能与Foo 1__堆栈)。
这将给出以下分组及其对应的Bar和
在这种情况下,正确的分组将是Foo 1和Foo 3。
提前感谢!
发布于 2019-06-27 22:28:49
如果我正确理解您的问题,下面将返回正确的分组。
void Main()
{
var data = new[] {
new Foo {FooId = 1, Bar = 5, Stackability = new int[] {2, 3} },
new Foo {FooId = 2, Bar = 2, Stackability = new int[] {1, 3} },
new Foo {FooId = 3, Bar = 6, Stackability = new int[] {1} } };
var result = data
.Select(d => new
{
Foo = d,
Matches = data.Where(dm => dm.Stackability.Contains(d.FooId))
})
.Select(d => new
{
d.Foo,
Narrowed = d.Matches.Where(m => d.Foo.Stackability.Contains(m.FooId))
})
.SelectMany(d => d.Narrowed.Select(n => new { Foos = new List<Int32> { d.Foo.FooId, n.FooId}, BarSum = d.Foo.Bar + n.Bar}))
.OrderByDescending(d => d.BarSum)
.First();
Console.WriteLine($"{{ {String.Join(", ", result.Foos.Select(f => $"Foo {f}"))} }} - Bar == {result.BarSum}");
}
public class Foo
{
public int FooId { get; set; }
public int Bar { get; set; }
/// <summary>
/// Contains list of FooId
/// </summary>
public int[] Stackability { get; set; }
}因为它返回以下内容:
{ Foo 1,Foo 3}- Bar == 11
https://stackoverflow.com/questions/36778516
复制相似问题