0

I have made a small application to practice lambda expressions. I am new to using this technique and I want to become familiar with using them in my day to day coding as I realise how powerful they can be.

I have made a Class named Pet each pet has a Name and an Age I have added 4 pets to my Pet class.

I want to get the pets name who has an age of 1 using a Where and Select clause. However when I run my code instead of returning the pets name I get System.Collections.Generic.List 1 [System.String]

My code is as follows

Pet class

   class Pet
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

Program Class

        var pets = new Pet[]
        {
            new Pet {Name="Sharo", Age=8 },
            new Pet {Name="Rex", Age=4 },
            new Pet {Name="Strela", Age=1 },
            new Pet {Name="Bora",Age=1 }
        };

p = pets.Where(pet => pet.Age == 1).Select(pet => pet.Name).ToList();

Console.WriteLine(p);
3
  • What output you expect? The linq query is returning you the collection of result. In your code this will be collection of names. You need to loop thru it to get the actual value. If you are sure that the linq query will return only one result then you should use FirstOrDefault instead of ToList. This will give you the first item of the result collection Commented Sep 21, 2017 at 11:29
  • Maybe you expect only one, then use First or Single(throws exception if more than one). string petname = pets.First(p => p.Age == 1).Name;. Note that this throws a NullRefernceException if there are none, you can use Console.WriteLine(pets.FirstOrDefault(p => p.Age == 1)?.Name); Commented Sep 21, 2017 at 11:35
  • If you want to practice Lambda expressions(delegate type or expression type). What I would suggest is implementing you own Where, Select, GroupBy... method extensions. Lambdas are much more useful then LINQ. And basic implementation is the linq methods is not all that difficult to make. Commented Sep 21, 2017 at 11:35

2 Answers 2

2
Console.WriteLine(p)

implicitely calls the ToString() method of object p, which by default returns the typename.

Use instead

Console.WriteLine(String.Join(",", p));

The rest of your code looks perfectly correct.

note : if you want to practice lambdas a bit more, you can get the string concat with linq's aggregate :

Console.WriteLine(p.Aggregate((current, next) => current + ", " + next));
Sign up to request clarification or add additional context in comments.

Comments

0

When you do ToList you have List<String>

Instead you can do

foreach(var pet in p)
    Console.WriteLine(p.Name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.