Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

c# - LINQ - query does not return an object from a list of objects

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();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 should now contain either a single MyClass instance or a null.

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

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.


Things to check

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

  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...