Reputation: 13
I'm trying to display the names of 10 people in a windows form app textbox. The last line of code gives me the following 2 errors:
The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments.
Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string[]'.
Can someone explain the errors and a how to fix them?
public class FullName
{
public string name;
public string surname;
}
int i;
List<FullName> namesList = new List<FullName>();
for (i = 0; i < 10; i++)
{
namesList.Add(new FullName { name = "John", surname = "Adams" });
}
txt_names.Text = String.Join(" ", namesList);
Upvotes: 1
Views: 57
Reputation: 467
You are passing Generic list as the second argument to String.Join(), while it accepts an array of strings.
So Instead of
txt_names.Text = String.Join(" ", namesList);
txt_names.Text = String.Join(" ", namesList.Select(x=> $"{x.Name} {x.SurName}");
and the rest will go fine.
Upvotes: 0
Reputation: 861
Use override to make string beautify
public class FullName
{
public String Name { get; set; }
public String SurName { get; set; }
public override string ToString()
{
return String.Format("{0} {1}", Name, SurName);
}
}
after you override ToString() method you can just call class to print it.
List<FullName> Names = new List<FullName>();
for ( int i = 0; i < 10; i++ )
{
Names.Add(new FullName() { Name = "John", SurName = "Smith" });
}
Console.WriteLine(String.Join("\r\n", Names));
Result >
John Smith
John Smith
John Smith
John Smith
John Smith
John Smith
John Smith
John Smith
John Smith
John Smith
Upvotes: 1
Reputation: 493
String.Join expects a list of strings to join. You are giving a list of FullName right now.
You can try:
String.Join(",", namesList.Select(m => m.name).ToArray());
And if you want name and surname both, you can simply append it:
String.Join(",", namesList.Select(m => m.name + m.surname).ToArray());
Upvotes: 1