Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET : select multiple values in query using Linq

I need to return an IEnumerable. Here is the working code:

public IEnumerable<String> ReturnStudentsAsString(int vak, int klasgroep)
    {
        return (from s in Students
                orderby s.Naam, s.Voornaam
                select s.Naam);
    }

That works perfect! Now, I want to return the street and the postal code as well... So I created an anonymous type:

public IEnumerable<String> ReturnStudentsAsString(int vak, int klasgroep)
    {
        var test = (from s in Studenten
                orderby s.Naam, s.Voornaam
                select new 
                {
                    StudentNumber = s.StudentNumber,
                    Name = s.Name,
                    Street = s.Street,
                    PostalCode = s.PostalCode,
                    City = s.City
                });
        return test;

But it gives me an error... How could I fix it?

Thanks in advance!

like image 554
Lorenzo Avatar asked Apr 17 '26 08:04

Lorenzo


1 Answers

Your method is returning an IEnumerable<string>. You've changed your return value to a new anonymous type, rather than a collection of strings.

To fix, you could:

  • create a class, and instantiate & return IEnumerable<MyClass> (preferred!)
  • return IEnumerable<dynamic> if you're using .NET 4. and you don't care for static typing up the call stack.
like image 149
p.campbell Avatar answered Apr 18 '26 22:04

p.campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!