c# - 在 x.Kind = "value"时选择 Top(x)

标签 c# linq loops

只要列表顶部的项目具有具有特定值的属性,如何选择列表顶部。

我需要 Linq 语句来查看序列中是否有中断,并且只返回前两项。问题是我不确切知道有多少项将具有正确的属性值。

我一直在使用 LinqPad 4 解决这个问题。下面的代码是 LinqPad 4 的副本和过去。结果“q”不应包含 EffectiveDate 为 4/5/2011 的 SomeData,因为 Kind 属性在 hsc2 上是“KindTwo”。

我正在尝试找到“Kind”最常出现的值,然后只获取与该值匹配的最高记录,直到找到与该值不匹配的记录为止。

void Main()
{
    var hsc1 = new SomeData {EffectiveDate = new DateTime(2011,4,5), Kind = "KindOne"};
    var hsc2 = new SomeData {EffectiveDate = new DateTime(2011,4,10), Kind = "KindTwo"};
    var hsc3 = new SomeData {EffectiveDate = new DateTime(2011,4,20), Kind = "KindOne"};
    var hsc4 = new SomeData {EffectiveDate = new DateTime(2011,4,25), Kind = "KindOne"};

    var all = new [] {hsc1, hsc2, hsc3, hsc4};

    var lastSomeData = all.OrderByDescending((x) => x.EffectiveDate).First();

    lastSomeData.Dump();

    var q = from h in all 
            where h.Kind == lastSomeData.Kind
            orderby h.EffectiveDate descending 
            select h;

    q.Dump();
}

// Define other methods and classes here
class SomeData
{
    public DateTime EffectiveDate {get;set;}
    public string Kind {get;set;}
}

最佳答案

您正在寻找 TakeWhile方法

DateTime filterDate = new DateTime(2011, 4, 5);
var top = q.TakeWhile(x => (DateTime.Compare(x, filterDate) != 0));

关于c# - 在 x.Kind = "value"时选择 Top(x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5825629/

相关文章:

c# - 如何使用 Linq 或 Lambda 连接一对多表并将扁平化结果投影为匿名类型

php - 使用 PHP 进行 MySQL 多用户多表查询

java - 从文本文件向Java中的对象分配属性

c# - 我如何获得屏幕方向?

c# - 这是使用 LINQ 创建频率表的最佳方式吗?

c# - 更改 elasticsearch serilog 接收器 http 内容 header

LINQ to CRM - OR in Where 子句

php - 如何在 3 个不同的表中使用 while 循环来回显数据库的特定列

c# - Excel 之上的 Windows 窗体

c# - 自定义 TFS Web 应用程序无法在 IIS 上运行