Linq 查询嵌套列表

本文关键字:列表 嵌套 查询 Linq | 更新日期: 2023-09-27 18:33:40

我有一个列表,每个Foo包含一个列表,

我想根据日期时间列表中的条件过滤列表中的项目。 例如,我想获取嵌入列表中具有重复日期时间的所有Foo项目。

我已经尝试了很多事情,但我认为我的逻辑在我想要实现的目标中略有缺陷。 任何帮助,不胜感激。

谢谢。

Linq 查询嵌套列表

我相信

你正在寻找这样的东西:

List<Foo> foos = new List<Foo>();
Random r = new Random();
for (int i = 0; i < 100; i++)
{
    foos.Add(new Foo { Bar = DateTime.Now.Date.AddDays(r.Next(0, 365)) });
}
IList<Foo> filteredFoos = foos.Where(f1 => foos.Count(f2 => f2.Bar == f1.Bar) > 1).ToList();

Foo看起来像这样:

class Foo
{
    public DateTime Bar { get; set; }
}

这可能会对你有所帮助(即使很难弄清楚你有什么/需要什么,正如安德鲁已经说过的那样):

public class Foo
{
    public Foo(IEnumerable<DateTime> dates)
    {
        this.Dates = new List<DateTime>(dates);
    }
    public IList<DateTime> Dates { get; private set; }
    public static IEnumerable<Foo> FindFoos(IList<Foo> source)
    {
        return from f in source
               where f.Dates.Distinct().Count() < f.Dates.Count
               select f;
    }
}

免责声明:它根本没有效率。使用不同的数据结构或更复杂的算法将加快速度。

尝试

var duplicateDateFoos = foos.Where(foo => foo.DateTimes.GroupBy(d => d).Any(dateGroup => dateGroup.Count() > 1));

对于每个 foo,这将按其日期时间值对日期时间列表进行分组。如果对于特定的 foo,存在一个包含多个项目的分组 - 即此 foo 的 DateTimes 中至少有两个条目具有相同的值 - 那么这个 foo 将被添加到 duplicateDateFoos 列表中。