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

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

我一直在使用LinqPad 4解决此问题。下面的代码是LinqPad 4的副本和过去的代码。结果“ q”不应包含有效日期为4/5/2011的SomeData,因为hsc2上的Kind属性为“ 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的人,因此请不要将我的答案标记为已接受。

using System;
using System.Linq;
namespace stackoverflow.com_questions_5825629_select_topx_while_x_kind_value
{
    class Program
    {
        static 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();

            var q = (from h in all
                     orderby h.EffectiveDate descending
                     select h).TakeWhile(x => x.Kind == lastSomeData.Kind);

            var result = q.ToArray();

            foreach (var item in result)
                Console.WriteLine(item);
            Console.WriteLine("");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        // Define other methods and classes here
        class SomeData
        {
            public DateTime EffectiveDate { get; set; }
            public string Kind { get; set; }
            public override string ToString()
            {
                return string.Format(@"new SomeData {{ EffectiveDate = new DateTime({0}, {1}, {2}), Kind = ""{3}"" }};", EffectiveDate.Year, EffectiveDate.Month, EffectiveDate.Day, Kind);
            }
        }
    }
}

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

10-10 07:35