C# 在列表中追加列表
本文关键字:列表 追加 | 更新日期: 2023-09-27 18:33:15
我有一个循环,可以在我的数据库中获取一些国家/地区,根据条件,我需要在该数组中输入一些值,然后在最后有一个包含所有值的最终列表。请注意,我需要在循环内进行 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#我卡住了!
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,它返回一个"级别"标签,但代码更少
public string level {
get {
return countCities <= 1 ? "low" : (countCities == 2 ? "medium" : "high");
}
}
使用泛型列表,这些列表可以轻松扩展:
List<string> stringarray = new List<string>();
stringarray.Add("New entry");
像这样组合它们:
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>();
如果需要,您甚至可以创建自定义类"CustomClass"并列出:
List<CustomClass> lcc = new List<CustomClass>();
我会删除"搜索文本"
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()...
}
是诀窍!
如果您没有好的答案,请不要投票反对,并尝试提出自己的问题。谢谢