Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
model :
C#
public class hello
{
    public list<string> mobilenumbers {get;set;}
    public string name {get;set;}
}


controller :
C#
string user = (string)Tempdata["user"]
var result =db.tblname.Where(em=>em.name==user).ToList()
list<hello> lst = new list<hello>;
foreach(var item in result)
{
   hello obj = new hello();
   obj.name = item.name;
   var mobile = db.tblmobile.where(em=>em.name==item.name).ToList();
   foreach(var item1 in mobile)
   {
    obj.mobile.Add(item1.mobile); 
   }
}


What I have tried:

it is throwing null reference when adding mobile numbers . is there a easy way to get these multiple numbers for a single name user.
Posted
Updated 19-Apr-16 0:41am

Check for Null value in the collection

C#
 if(result !=null)
foreach(var item in result)


C#
if(mobile!=null)
 foreach(var item1 in mobile)
 
Share this answer
 
Your hello class has a property mobilenumbers but the code is using mobile so it won't even compile, I assume this is a typo? Where you try and add the mobile number if you use the debugger you'll see that obj.mobilenumbers is null so you can't call any methods on it like "add". Objects like Lists etc only exist when you create them, so you need to create the list before you use it

C#
string user = (string)Tempdata["user"]
var result =db.tblname.Where(em=>em.name==user).ToList()
list<hello> lst = new list<hello>;
foreach(var item in result)
{
   hello obj = new hello();
    // create the list before you can use it
   obj.mobilenumbers = new List<string>();
   obj.name = item.name;
   var mobile = db.tblmobile.where(em=>em.name==item.name).ToList();
   foreach(var item1 in mobile)
   {
    obj.mobilenumbers.Add(item1.mobile); 
   }
}
 
Share this answer
 
Comments
Himaan Singh 19-Apr-16 7:05am    
it works thanks a ton

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900