在c#的list集合对象中,firstordefault方法可以用于查找list集合中符合条件的第一个元素,如果需要根据条件查找到list集合中的所有符合条件的元素对象集合,则需要使用到list集合的扩展方法where()方法,where方法的书写方式为lambda表达式的书写形式,通过where方法查找出符合条件的元素后再通过tolist方法可转换回原来的list集合对象类型。

举例如下,list集合testlist为自定义类的list集合对象,首先往list集合中写入3条记录,具体如下:

   list<testmodel> testlist = new list<consoleapplication1.testmodel>();
            testlist.add(new testmodel()
            {
                 index=1,
                 name="index1"
            });
            testlist.add(new testmodel()
            {
                index = 2,
                name = "index2"
            });
            testlist.add(new testmodel()
            {
                index = 2,
                name = "index2"
            });

  如果想从 list集合testlist对象中查找出index=2的所有元素对象,并放到一个新的list集合中,可使用下面的语句实现:

var resultlist = testlist.where(t => t.index == 2).tolist();

其中t=>t为lambda表达式的特殊写法,t代表testlist集合中的元素对象。最后计算结果resultlist集合中含有2个元素对象。

 

备注:原文转载自博主个人站it技术小趣屋,原文链接c#中通过where方法查找出所有符合条件的元素集合_it技术小趣屋。