C#在列表中附加列表
我有一个循环,它获取数据库中的一些国家,根据条件,我需要在该数组中放入一些值,然后在最后有一个包含所有值的最终列表注意,我需要在循环内进行3次检查(级别1、2和3):C#在列表中附加列表,c#,C#,我有一个循环,它获取数据库中的一些国家,根据条件,我需要在该数组中放入一些值,然后在最后有一个包含所有值的最终列表注意,我需要在循环内进行3次检查(级别1、2和3): var countries= db.Countries .Where(x => x.name.Contains(searchText)) .OrderByDescending(o => o.id); foreach (var country in countries)
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中我被卡住了 使用通用列表,可以轻松扩展:
List<string> stringarray = new List<string>();
stringarray.Add("New entry");
List stringarray=new List();
stringarray.Add(“新条目”);
将它们按如下方式组合:
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>();
List lls=新列表();
lls.Add(stringarray);
//如果要重用startingarray,请不要忘记重新初始化它。
stringarray=新列表();
如果需要,您甚至可以创建自定义类“CustomClass”,并列出:
List<CustomClass> lcc = new List<CustomClass>();
List lcc=new List();
其中CustomClass有一个简单的getter,它返回一个“level”标签,可以实现您想要的功能,但代码更少
public string level {
get {
return countCities <= 1 ? "low" : (countCities == 2 ? "medium" : "high");
}
}
公共字符串级别{
得到{
return countCities我会删除“SearchText”
我找到了
for (var index = 0; index <= countries.Count()-1; index++)
{ if ()...
else if()...
}
for(var index=0;index什么类型是customArray
?现在我们通常使用通用集合而不是数组它是一个列表:list customArray=new list();我创建这个类是为了让我的json数据格式化为CustomClass中声明的值,那么为什么你的问题会提到数组?如果不是数组,为什么要命名你的类customArray
?代码中缺少什么?它似乎已经选择了数据。可以添加的一件事是调用db.Countries.Include(x=>x.Cities)。Where(…)
以避免循环中的多个选择。您的代码有什么问题/您试图实现什么?在您的示例中,只有一个项目是集合customArray
所以组合在哪里?我更新了我的问题。我仍然需要进行检查(3次检查)。查看我的更新问题。谢谢。我想知道您最终使用了什么作为查询代码。这些答案对您有用吗?
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() }
);
for (var index = 0; index <= countries.Count()-1; index++)
{ if ()...
else if()...
}