The Muffin Man
The Muffin Man

Reputation: 20004

Help building up LINQ query when using anonymous types

I've started out with:

IQueryable<Author> authors2 = db.Authors;

Then I build up authors2 in multiple if statements, here's one of them

authors2 = authors2.Where(t => t.ItemAuthors.Any(b => b.Item.CategoryItems.Any(z => z.categoryID == int.Parse(ddlCategory.SelectedValue))));

Then finally I would like to append this to the end of the built up where clauses

authors2.OrderBy(x => x.text).Select(x => new
            {
                authorText = string.Format("{0} ({1})",x.text, x.ItemAuthors.Count())
            });

To bind a control like this:

ddlAuthor.DataSource = authors2;
            ddlAuthor.DataTextField = "authorText";
            ddlAuthor.DataBind();

Apparently the compiler is not very happy about my select new statement. How can I rewrite this to achieve the same goal? I believe this is called creating an anonymous type.

It says an explicit conversion exists(are you missing a cast?) I can't figure out how to cast it.

Upvotes: 1

Views: 74

Answers (1)

Nasmi Sabeer
Nasmi Sabeer

Reputation: 1380

In your third statement, the returned type is not same as authors2 because the Select projects a different type other than Author

So assign the value to a new variable

var authorsFinal = authors2
                    .OrderBy(x => x.text)
                    .Select(x => new
                    {
                      authorText = string.Format("{0} ({1})",
                                                 x.text, 
                                                 x.ItemAuthors.Count())
                    });

Upvotes: 1

Related Questions