I am learning C# and have been taking a lot of online courses. I am looking for a simpler/neater way to enumerate a list within a list.
In python we can do something like this in just one line:
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
Does it have to involve lambda and Linq in C#? if so, what would be the solution? I tried it with Dictionary in C# but my gut tells me this is not a perfect solution.
List<List<string>> familyListss = new List<List<string>>();
familyListss.Add(new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" });
familyListss.Add(new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" });
familyListss.Add(new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" });
Dictionary<int, List<string>> familyData = new Dictionary<int, List<string>>();
for (int i = 0; i < familyListss.Count; i )
{
familyData.Add(i, familyListss[i]);
}
CodePudding user response:
Just a constructor will be enough:
List<List<string>> familyListss = new List<List<string>>() {
new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" },
new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" },
new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" }
};
If you want to mimic enumerate
you can use Linq, Select((value, index) => your lambda here)
:
using System.Linq;
...
var list = new List<string>() {
"a", "b", "c", "d"};
var result = list
.Select((value, index) => $"item[{index}] = {value}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
item[0] = a
item[1] = b
item[2] = c
item[3] = d
CodePudding user response:
Are you taking about something like this?
int i = 0;
familyListss.ForEach(f => { familyData.Add(i, f);i ; });
This is refactored from
int i = 0;
foreach (var f in familyListss)
{
familyData.Add(i, f);
i ;
}
With a small extension method, you can build in an index to foreach to make it one line. Extension methods are worth exploring, and can take annoying, repeated tasks out of your way.
Also see this question: C# Convert List<string> to Dictionary<string, string>