C#在列表中追加列表

时间:2016-02-03 19:58:49

标签: c#

我有一个循环,可以在我的数据库中获取一些国家/地区,并根据条件我需要在该数组中放置一些值,然后在最后有一个包含所有值的最终列表。 请注意,我需要在循环中进行3次检查(级别1,2和3):

    var countries= db.Countries
        .Where(x => x.name.Contains(searchText))
        .OrderByDescending(o => o.id);

    foreach (var country in countries)
    {
        if(country.Cities.Count() == 1)
        {
            customList.Add(new CustomClass
            {
                countCities = 1,
                name = country.name,
                level = "low"
            });
        }
       else if (country.Cities.Count() == 2)
        {
            customList.Add(new CustomClass
            {
                countCities = 2,
                name = country.name
                 level = "medium"
            });
        }


        else if (country.Cities.Count() == 3)
        {
        customList.Add(new CustomClass
        {
            countCities = 3,
            name = country.name
             level = "high"
        });
      }
    }

最后我想要这样的东西:

   [ { name="Canada",  countCities = 1, level ="low"}, { name = "Australia",  countCities = 2, level ="medium"},  { name = "China",  countCities = 3, level ="high"} ]

在PHP中我知道怎么做,但是c#im卡住了!

4 个答案:

答案 0 :(得分:1)

customArray.AddRange( db.Countries
    .Where(x => x.name.Contains(searchText))
    .OrderByDescending(o => o.id)
    .Select(c => new CustomClass { name = c.name, countCities = c.Cities.Count() })
);

CustomClass有一个简单的getter返回一个'level'标签就可以做你想要的但代码更少

public string level {
    get {
        return countCities <= 1 ? "low" : (countCities == 2 ? "medium" : "high");
    }
}

答案 1 :(得分:0)

使用通用列表,可以轻松扩展:

n

将它们组合在一起:

List<string> stringarray = new List<string>();

stringarray.Add("New entry");

如果您愿意,您甚至可以创建自定义类&#39; CustomClass&#39;并列出:

List<List<string>> lls = new List<List<string>>();

lls.Add(stringarray);

// Don't forget to re-initialize the startingarray if you want to reuse it.
stringarray = new List<string>();

答案 2 :(得分:0)

我会删除“SearchText”

 customArray.AddRange(from con in db.Countries
                      join cit in db.Cities on con.id equals cit.id
                      orderby con.id
                      select new CustomClass { name= con.name, countCities= con.Cities.Count()  }
                      );   

答案 3 :(得分:0)

我找到了它!

  for (var index = 0; index <= countries.Count()-1; index++)
             {    if ()...

   else if()...

 }

是诀窍!

如果你没有好的答案并且试着提出自己的问题,请不要投票。感谢