Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a newbie to LINQ and I am aware this is (should be?) a simple question, but I am struggling with the syntax of a simple LINQ query. The following cut-down code shows what I am trying to achieve:

public class Fruit
{
    public int ID { get; set; } = 0;
    public Name { get; set; } = String.Empty;
}

public class Fruits
{
    public List<Fruit> ListOfFruits = new List<Fruit>()
    {
        new Fruit { ID = 0, Name = "Apple" },
        new Fruit { ID = 1, Name = "Orange" },
        new Fruit { ID = 2, Name = "Banana" },
    }

    public int GetIDFromName( string fruitName )
    {
        // What goes here?
    }
}


As a beginner at this, I'd appreciate any advice at all. In particular, I would like a solution that uses the special LINQ keywords ('select', 'where', etc.) and also the standard C# LINQ functions ( Select(), Where(), etc.) so I can compare the two approaches.

There seems to be very few examples that show the two approaches side-by-side for comparison, and I am also confused about when one approach is better than the other. For simple consistency, I'd like to pick one way and stick with it.

Kind wishes ~ Patrick

What I have tried:

I have tried expressions like...

C#
ListOfFruits.Select( f => f.ID ).Where( ... )


...but I can't even get this to compile because it seems by specifying just the ID in the Select clause, I stop myself being able to reference the Name in the Where clause.
Posted
Updated 18-Jan-17 23:45pm

C#
ListOfFruits.FirstOrDefault(x => x.Name == "Apple").ID

You could also load the FirstOrDefault into an object and check for null before trying to access the id.

As suggested, in order to avoid a NullRef exception you can do a couple of things:

If you are using a version of VS with the Roslyn compiler:

C#
ListOfFruits.FirstOrDefault(x => x.Name == "Apple")?.ID


Otherwise the more verbose method:

C#
var fruit = ListOfFruits.FirstOrDefault(x => x.Name == "Apple");
if (fruit != null)
{
     return fruit.ID;
}

return 0;


This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First(). Single expects a single response that has to be there, I find myself gravitating to FirstOrDefault more often than not.
 
Share this answer
 
v3
Comments
Thomas Daniels 18-Jan-17 14:24pm    
This is right, but note that it will throw an exception when the return value of FirstOrDefault is null.
eddieangel 18-Jan-17 14:31pm    
Improved the solution to account for that case explicitly, thanks for the suggestion.
Since you asked for both syntax forms:
C#
public int GetIDFromName( string fruitName )
{
  // LINQ functions:
  Fruit f = ListOfFruits.FirstOrDefault(x => x.Name == fruitName);
  // LINQ SQL-ish:
  Fruit f = (from x in ListOfFruits where x.Name == fruitName select x).FirstOrDefault();
  // (common to both):
  return f != null ? f.ID : -1;   // some value to indicate no such fruit
}
This is not a particularly good case for comparing one syntax with the other...
 
Share this answer
 
Comments
Patrick Skelton 19-Jan-17 4:25am    
You comment this is not a particularly good case for comparing the two syntax variants. Is it true to say then that, if I want consistency, I might do better staying with the plain C# syntax? Is it more flexible than the pure SQL-ish form?
Matt T Heffron 24-Jan-17 12:45pm    
(I've been "off the grid"...)
In the big picture, I think that each of the two forms have their advantages, and there are some queries that can be expressed only in the method syntax (like the "FirstOrDefault()" above).
For example, (for me) the SQL form is better if there are JOINs.
This is not a point where you should be strict on overall consistency of choice of syntax form.
Use what makes sense in each context.
Patrick Skelton 24-Jan-17 13:22pm    
Thank you, Matt. That is very helpful.
We can also user First instead of FirstOrDefault.We can write the above code like this

public int GetIDFromName( string fruitName )
{
// LINQ functions:
Fruit f = ListOfFruits.First(x => x.Name == fruitName);
// LINQ SQL-ish:
Fruit f = (from x in ListOfFruits where x.Name == fruitName select x).First();
// (common to both):
return f != null ? f.ID : -1; // some value to indicate no such fruit
}
 
Share this answer
 
Comments
F. Xaver 19-Jan-17 7:09am    
.First will throw an Exception if there is no Fruit with that Name, so -1 is never returned
[no name] 19-Jan-17 7:23am    
Okay,Thanks Xavier.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900