如何在类的list属性中添加字符串元素 [英] How to add strings elements in the list property of a class

查看:1539
本文介绍了如何在类的list属性中添加字符串元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号:

model :

public class hello
{
    public list<string> mobilenumbers {get;set;}
    public string name {get;set;}
}





控制器:



controller :

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.

推荐答案

检查 Null 值在集合中



Check for Null value in the collection

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







if(mobile!=null)
 foreach(var item1 in mobile)


你的hello类有一个属性mobilenumbers但代码是使用mobile,所以它甚至不会编译,我认为这是一个错字?如果你使用调试器尝试添加手机号码,你会发现obj.mobilenumbers为null所以你不能像add那样调用任何方法。像列表等对象只在您创建它们时才存在,因此您需要在使用它之前创建列表



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

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); 
   }
}


这篇关于如何在类的list属性中添加字符串元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆