【问题标题】:Filter list of object by value of property of nested list equals value of same property of another element of the nested list按嵌套列表的属性值过滤对象列表等于嵌套列表的另一个元素的相同属性的值
【发布时间】:2016-02-02 17:05:06
【问题描述】:

好的,我有这门课:

public class Person
{
    public int Id { get; set; }
    public string SpecialNumber { get; set; }
    public IQueryable<Game> Games { get; set; }
}  

还有这些类:

public class Game
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal? RamNeeded { get; set; }
    public Town Town { get; set; }
}

public class Town
{
    public int Id { get; set; }
    public string TownName { get; set; }
    public string CountryName { get; set; }
    public string StateName { get; set; }
}

我需要显示来自 People (IQueryable&lt;Person&gt;) 的 Person 中的 SpecialNumber,其中 的游戏RamNeeded 最大,谁有游戏:

  1. 来自超过 2 个不同的城镇在一个
  2. 来自一个国家的不同国家(这意味着至少有两个不同国家的游戏)。
  3. 来自不同的国家(这意味着至少有两个不同国家的游戏)。

我需要在 LINQ 或 SQL 上进行此查询。希望你能帮忙。

【问题讨论】:

  • 造成你困难的部分是什么?
  • (1), (2), (3) 是过滤条件,对吗?它们是如何组合的 - ANDOR
  • @DanBracuk 首先如何比较 LINQ 中城镇名称的值
  • @IvanStoev 是的,它们被组合为 AND

标签: c# sql linq linq-to-sql


【解决方案1】:

任何时候您需要对具有相同属性值的集合元素做某事,您可以使用GroupBy 方法(或查询语法中的group 子句)。

然后您可以对每组元素使用不同的聚合函数。例如,在您的情况下,Count 可用于检查组是否包含特定数量的项目。

话虽如此,有问题的查询可能是这样的

IQueryable<Person> persons = ...;

var query =
    from person in persons
    let countryGroups = person.Games.GroupBy(game => game.Town.CountryName)
    where countryGroups.Count() > 1 // (3)
        && countryGroups.Any(countryGroup =>
            countryGroup.GroupBy(game => game.Town.StateName).Count() > 1 // (2)
            && countryGroup.GroupBy(game => game.Town.StateName).Any(stateGroup =>
                stateGroup.GroupBy(game => game.Town.Id).Count() > 2)) // (1)
    let RamNeeded = person.Games.Sum(game => game.RamNeeded) // in case you need to include it in the select
    orderby RamNeeded descending
    select person.SpecialNumber;

var result = query.FirstOrDefault();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2014-09-17
    • 2021-09-27
    • 2023-03-22
    • 1970-01-01
    • 2011-05-18
    相关资源
    最近更新 更多