![](/img/trans.png)
[英]How to combine two resources value in one in gridview in asp.net
[英]How to combine two lists in one with key and value to be duplicated in ASP.NET Core MVC
我有两个来自表单的列表,一个包含人名,另一个包含城市
像这样
public IActionResult Index([FromForm] List<string> people,[FromForm] List<string> city)
{
}
现在假设我有三个人 John、Sarah 和 Tom
我有四个城市伦敦,巴黎,DC,罗马
因此,如果用户选择 John 和 Sarah 以及 London, Paris, DC 作为城市
这意味着约翰拥有所有三个城市,而莎拉拥有所有三个城市
我想要的是将两个列表(人和城市)组合在一起以获得这个结果,对于每个选择的人,他们将选择所有城市,如我上面提供的示例
我尝试使用 Dictionary 但因为它必须有唯一的键,所以它不起作用,也尝试了 ZIP,但它没有做我想要的。
有没有办法可以实现这个!
到目前为止我尝试过的
public IActionResult Index([FromForm] List<string> people,[FromForm] List<string> city)
{
List<person> personInfo = =new List<person>();
var results =people.Zip(city).ToList();
for(int i=0;i<results.Count;i++)
{
personInfo.add(new person()
{
name=results[i].First,
city=results[i].Second
}
}
}
您可以使用元组和SelectMany
。
var results = people.SelectMany(person => cities.Select(city => (person, city))).ToList();
这将返回一个List<(string, string)>
。
现在你可以像这样循环它:
foreach (var result in results)
{
var person = result.person;
var city = result.city;
}
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.