C# – Converting Int to String inside a LINQ expression

clinqlinq-to-entities

I'm creating a SelectList to populate a dropdown list from a LINQ query. This works:

// my temp class for including the member count
public class GroupWithCount
{
    public string group_name { get; set; }
    public int group_id { get; set; }
    public int members { get; set; }        
}

var groups = from g in DB.Groups
     where g.user_id == user_id
     let mC = (from c in DB.Contacts where c.group_id == g.group_id select c).Count()
         select new GroupWithCount
         {
             members = mC,
             group_id = g.group_id,
             group_name = g.group_name
         };
 model.Groups = new SelectList(groups, "group_id", "group_name");

However, I want the selectItem text to be in the format "group_name (members)", but I can't seem to do that. if I try

         select new GroupWithCount
         {
             members = mCount,
             group_id = g.group_id,
             group_name = g.group_name + mCount 
         };

I get "Unable to cast the type 'System.Int32' to type 'System.Object'. " If I try

             group_name = g.group_name + mCount.ToString()

I get "LINQ to Entities does not recognize the method 'System.String ToString()' method". If I try

             group_name = string.Format("{0}{1}", g.group_name,mCount)

I get "LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)' method".

It just won't let me convert that Int32 into a string. It seems like the only option is to create a foreach method that iterates through the GroupWithCount objects and creates a collection of SelectListItems, but that's madness. There must be a better way!

Best Answer

If framework is not allowing you to make the change in LINQ query, you can then achieve it once you have received the resultset. In the resultset, you are already having "mCount" value, you can iterate over the collection and modify the value of group_name accordingly. For e.g.

var groups = // your query;

groups.ForEach(item => item.group_name = item.group_name + item.mCount.ToString);