开发者

ASP.NET : select multiple values in query using Linq

开发者 https://www.devze.com 2023-03-26 21:07 出处:网络
I need to return an IEnumerable. Here is the working code: public IEnumerable<String> ReturnStudentsAsString(int vak, int klasgroep)

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!


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.


It is no longer an IEnumerable<String>. You'd have to return an IEnumerable<object> to pass the anonymous type back from your query.

Edit: As others have suggested, a better approach would probably be to define a static type to hold the values you want to return. Alternately, since this is basically a one-liner query, you could do it in-line wherever you're using this method instead of creating a specialized method for it.


The error is because of your return type is stated as IEnumerable<String>. You are no longer returning an enumerable of string. You are trying to return an anonymous type, which is possible, but it is hacky. Instead, you should create a new type, maybe Address which contains all the members you need. You should also rename your method as it is no longer returning strings, but complex types with multiple members. You can also change your return type to be IEnumerable<dynamic> if you are on .NET 4, but I think creating the new type is still the better approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号