开发者

Iterate over a collection of anonymous type in .NET

I'm OK with both C# and VB.NET

I have a function GetListOfBook, that returns LINQ to SQL result that has a collection of objects like the following:

var result = GetListOfBook();

  • Book is a Book object that property of Title and ISBN,
  • Category is a string
  • Author is an Author object that has Name and ID property.

So inside the collecton, it looks like this:

So inside the "result" collection it looks like this:

{Book = {Book}, Category = "English", Author = {Author}}
{Book = {Book}, Category = "English", Author = {Author}}
{Book = {Book}, Category = "Web Development", Author = {Author}}

I want to iterate over each item in the collection to get the Book title and ISBN, Category and 开发者_开发知识库the author name. Something like this:

foreach (var r in result)
{
    Respone.Write(r.Book.Title, r.Book.ISBN, r.Category, r.Auhtor.Name);
}

At the moment, I cannot iterate over the collection yet. Thank you for any suggestion.

Update:

Sorry for the trouble. This is actually working. I found the typo in the code.


You still need to use the correct syntax for foreach which requires you to specify a type for the loop variable. Since you can't name it explicitly, you need to use var which infers the type.

foreach (var r in result)
{
    Respone.Write(r.Book.Title, r.Book.ISBN, r.Category, r.Auhtor.Name);
}


You need to use an implicitly typed variable using var for the iteration variable within foreach, just as you presumably have for your query to start with:

var result = ...; // Your existing query

// r is implicitly typed here
foreach (var r in result)
{
    Response.Write(r.Book.Title, r.Book.ISBN, r.Category, r.Author.Name);
}

EDIT: Looking more closely at your code, I suspect this is the problem:

var result = GetListOfBook();

This can't be strongly typed, if it's returning an anonymous type... which means it must be returning something like IEnumerable or IEnumerable<object>. I suspect you'll need to create an appropriate "normal" type to contain the results from GetListOfBook - or perform the query in the same method that does the Response.Write call.


you can use reflection like this:

foreach (var r in result)
{
    PropertyInfo info = r.GetProperty("Category");
    Response.Write(info.GetValue(r, null));
}


You can use reflection to access the anonymous type's properties.
You can see some samples here: http://blogs.msdn.com/b/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

But you should do it really as a last resort if you MUST use anonymous types rather than explicit types.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜