0

I have two list that come from form one contains people name and the other one city

Like this

public IActionResult Index([FromForm] List<string> people,[FromForm] List<string> city)
{

}

Now let's say that I have three people John, Sarah and tom

And i have four cities London, Paris, DC, Rome

So, if the user choose John and Sarah and London, Paris, DC for city

This means John have all three cities and also Sarah have all three cities

What I want is combine the two lists (people and city) together to get this result which for each person chosen they will have all cities chosen like the example I provided above

I tried using Dictionary but since it must have unique key it didn't work and tried also ZIP but it doesn't do what I want.

Is there a way I can achieve this !!

what I tried so far

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
               }
        }
}

r2000_na
  • 49
  • 7
  • i would use a class that has the person and their selected city in it - don't try to separate them into different lists. – Daniel A. White Oct 23 '21 at 15:01
  • Seems that you like to get all combinations as a result from two lists. This will be called cartesian product and you could take a look into [this question](https://stackoverflow.com/q/4073713/1838048). But this is definitive not something you can save within a dictionary (due to the duplicate keys). – Oliver Oct 23 '21 at 15:08
  • But I'm getting this data from a database. There will be check box where user can select people and city . After selection I want to insert the data to the database. Yes I know dictionary won't work unfortunately – r2000_na Oct 23 '21 at 15:16

1 Answers1

0

You can use tuples, and SelectMany.

var results = people.SelectMany(person => cities.Select(city => (person, city))).ToList();

This will return a List<(string, string)>.

Now you can loop over it like this:

foreach (var result in results)
{
    var person = result.person;
    var city = result.city;
}

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples

Roy Berris
  • 1,502
  • 1
  • 17
  • 40