如何从开始到另一个列表的特定项目获取项目列表C#

时间:2018-10-13 08:34:06

标签: c# asp.net

我有一个这样的列表

             var s = new List<Dictionary<string, object>>
            {
                new Dictionary<string, object> {{"name", "t1"}, {"age", 12}},
                new Dictionary<string, object> {{"name", "t2"}, {"age", 22}},
                new Dictionary<string, object> {{"name", "t3"}, {"age", 32}},
                new Dictionary<string, object> {{"name", "t4"}, {"age", 42}},
                new Dictionary<string, object> {{"name", "t5"}, {"age", 52}},
                new Dictionary<string, object> {{"name", "t6"}, {"age", 62}},
            };

我如何获取包含从第一项到名称为“ t4”的项的列表

结果列表必须像这样:

            new List<Dictionary<string, object>>
            {
                new Dictionary<string, object> {{"name", "t1"}, {"age", 12}},
                new Dictionary<string, object> {{"name", "t2"}, {"age", 22}},
                new Dictionary<string, object> {{"name", "t3"}, {"age", 32}},
            };

1 个答案:

答案 0 :(得分:4)

您可以使用TakeWhile进行这种操作:

var result = source.TakeWhile(s => s["name"] != "t4").ToList();