LINQ-查询不会从对象列表中返回对象 [英] LINQ - query does not return an object from a list of objects

查看:57
本文介绍了LINQ-查询不会从对象列表中返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,我需要对其执行LINQ查询以找到一些特定的对象.

I have a list of objects and I need to execute a LINQ query on it to find some specific object.

class MyClass
{ 
    int id;
    int someOtherIdbutNotUnique;
}

var ls = myObjectList.Where(x => x.id==specificId 
                          && x.someOtherIdbutNotUnique == someOtherSpecificId)
                     .FirstOrDefault();

但是此查询不会返回MyClass对象.而且,我应该如何更改查询以获取满足给定条件的MyClass对象的列表.同时,想知道是否有任何优秀的LINQ教程可以让我从头开始.

But this query does not return a MyClass object. And also, how should I change the query to get list of MyClass objects that fulfill the given condition. At the same time, would like to know if there is any good LINQ tutorial where I can start from the scratch.

推荐答案

LINQ扩展方法采用谓词来过滤列表. WhereFirstFirstOrDefaultSingleSingleOrDefault(仅举几个例子)都使用相同的谓词.

LINQ extension methods take predicates to filter the list by. Where, First, FirstOrDefault, Single, SingleOrDefault (to name but a few) all take the same predicate.

一些Lambda表达式用来过滤列表.

Some Lambda expression to filter the list by.

public class MyClass
{
    public int Id {get;set;}
    public int Other {get;set;}
}

// myClasses is a populated list <-- this needs to be checked.
var result = myClasses.FirstOrDefault(x => x.Id == specificId && x.Other == specificOther);

Result现在应该包含一个MyClass实例或一个null.

Result should now contain either a single MyClass instance or a null.

如果省略OrDefault(),则如果找不到与谓词匹配的实例,则代码将引发错误.

If you omit the OrDefault() then your code will throw an error if it can't find an Instance that matches the predicate.

如果谓词返回多个项目,则First将选择第一个项目.如果将First交换为Single,并且谓词返回多个项目,则它将引发异常.

If the predicate returns several items, then First will pick the first item. If you swap First to Single and the predicate returns several items, it will throw an exception.

要检查的东西

  1. 您要执行查询的列表具有实例列表.

  1. The list you are performing the query against has a list of instances.

变量specificIdspecificOther具有列表中存在的值.您要做的最后一件事是想知道为什么它什么也不返回,实际上它实际上在执行您所要求的操作,而失败的原因是您用来查询错误位置的值.

The variables specificId and specificOther have values that exist in the list. The last thing you want to do is be wondering why it isn't returning anything, when actually it is doing exactly what you asked for and that the reason for failing is the values you were using to query with where wrong.

这篇关于LINQ-查询不会从对象列表中返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆