如何在mvc中检查列表是否包含特定字符串

时间:2018-03-14 16:40:58

标签: c# asp.net-mvc

我有一个像这样的列表

List<SegmentList> li = new List<SegmentList>();
li.Add(new SegmentList { Segname = "Select", SegId = 0 });
li.Add(new SegmentList { Segname = "Allergy", SegId = 1 });
li.Add(new SegmentList { Segname = "Skin", SegId =2 });
li.Add(new SegmentList { Segname = "Hair", SegId =3 });
li.Add(new SegmentList { Segname = "Fever", SegId = 4 });
li.Add(new SegmentList { Segname = "All", SegId = 5});

我有一个像这样的字符串&#34;过敏,皮肤,治愈,更好&#34; 在该列表中,单词&#34; Allergy&#34;和&#34;皮肤&#34;已经在那里了。 我想添加&#34; Cured&#34;并且&#34;更好&#34;在该列表中

我试过这个

public ActionResult Index(){

            List<SegmentList> li = new List<SegmentList>();
            li.Add(new SegmentList { Segname = "Select", SegId = 0 });
            li.Add(new SegmentList { Segname = "Allergy", SegId = 1 });
            li.Add(new SegmentList { Segname = "Skin", SegId =2 });
            li.Add(new SegmentList { Segname = "Hair", SegId =3 });
            li.Add(new SegmentList { Segname = "Fever", SegId = 4 });
            li.Add(new SegmentList { Segname = "USA", SegId = 5 });
            li.Add(new SegmentList { Segname = "All", SegId = 6 });
            SegmentList obj = new SegmentList();
            String data = db.Segments.Where(x=>x.Id== userid).Select(x => x.Segname).SingleOrDefault();
            List<string> segmentdata = new List<String>(data.Split(','));
            obj.List = segmentdata;
            string newdata = string.Empty;
            int count=6;
            foreach(string s in segmentdata)
            {
                newdata += s+",";
                count = count + 1;
                li.Add(new SegmentList { Segname = newdata.TrimEnd(','), SegId = count });
            }

            obj.seglist = li;
            ViewBag.List = li;
            return View(obj);
        }

2 个答案:

答案 0 :(得分:0)

也许是这样的:

List<SegmentList> li = new List<SegmentList>();
            li.Add(new SegmentList { Segname = "Select", SegId = 0 });
            li.Add(new SegmentList { Segname = "Allergy", SegId = 1 });
            li.Add(new SegmentList { Segname = "Skin", SegId = 2 });
            li.Add(new SegmentList { Segname = "Hair", SegId = 3 });
            li.Add(new SegmentList { Segname = "Fever", SegId = 4 });
            li.Add(new SegmentList { Segname = "All", SegId = 5 });

            List<string> stringList = new List<string>("Allergy,Skin,Cured,Better".Split(',')) ;

            foreach(var stirng in stringList)
            {
                if(li.Any(x => x.Segname.Equals(stirng)))
                {
                    li.Add(new SegmentList { Segname = stirng, SegId = li.Count });
                }
            }

答案 1 :(得分:0)

首先需要在一个数组中分隔字符串,可以使用方法Substring。 该阵列将包含过敏,皮肤,治愈和更好的4个元素。 对于每个元素,您可以验证主列表是否包含元素,否则您需要从ID中获取最大值,然后使用这些值插入主列表中。