我要做的是获取一个包含2个字段的IEnumerable
个对象,并查找其中一个字段中只有一个与第一个字段中的一个相关联。
换句话说,设置就像
using System;
using System.Linq;
using System.Collections.Generic;
public class Baz
{
public string Foo { get; set; }
public int Bar { get; set; }
}
public class Program
{
public void Main()
{
List<Baz> bazzers = new List<Baz>() {
new Baz { Foo = "A", Bar = 1 },
new Baz { Foo = "A", Bar = 3 },
new Baz { Foo = "B", Bar = 1 },
new Baz { Foo = "B", Bar = 1 },
new Baz { Foo = "C", Bar = 2 },
new Baz { Foo = "C", Bar = 2 },
new Baz { Foo = "D", Bar = 1 },
new Baz { Foo = "D", Bar = 1 }
};
// WANTED: An IEnumerable<Baz> that is like
// { Bar = 1, LoyalFoos = 2 }, (because both "B" and "D" are paired only with 1)
// { Bar = 2, LoyalFoos = 1 }, (because "C" is paired only with 2)
// { Bar = 3, LoyalFoos = 0 } (because there is no Foo that is paired only with the Bar 3)
}
}
使用LINQ有一个很好的方法吗?
答案 0 :(得分:2)
我不确定你想要什么输出。如果你正在为每个酒吧寻找忠诚的foos数量,也许是这样的事情:
<script src='<?php echo $config['dir_plugins']; ?>qroll.js'></script>
<script src='<?php echo $config['dir_plugins']; ?>validate.js'></script>
<script src='<?php echo $config['dir_plugins']; ?>hellios.js'></script>
或者如果你想要给每个忠诚的foo分组吧:
var result = bazzers
.Select(bazzer => bazzer.Bar)
.Distinct()
.Select(bar => new
{
Bar = bar,
LoyalFoos = bazzers
.GroupBy(bazzer => bazzer.Foo)
.Count(group => group.All(bazzer => bazzer.Bar == bar))
});