Reputation: 19184
What I want to do is similar to this, except that I have a more complex class (with multiple properties).
Convert a list to a string in C#
I have a class with multiple properties which is stored in a list
While populating this list, I also populate a |
seperated string with the name property, which is subsequently used by regex
So, can I just populate the list, and afterwards, easily build a |
seperated string from the Name
property of the class in the list?
Example Code
Class being populated:
public class Thing
{
public MyParentClass parent;
public string Name;
public List<string> OtherThings = new List<string>();
public Thing(string path)
{
// Here I set the Name property to the filename
Name = Path.GetFileNameWithoutExtension(path);
}
}
Populating code:
public List<Thing> Stuff = new List<Thing>();
public string AllThings = "";
void GetThings(files)
{
foreach (string f in files)
{
Stuff.Add(f)
AllThings = AllThings + Path.GetFileNameWithoutExtension(f) + "|";
}
}
So what I want to know is: Can I remove the AllThings = AllThings +
line and instead populate AllThings after all the classes are loaded?
If I try something like this:
AllCubes = string.Join("|", Stuff.ToArray());
I get
CS0121 The call is ambiguous between the following methods or properties: 'string.Join(string, params object[])' and 'string.Join(string, IEnumerable)'
Which is no suprise as I know it's not that simple - I just wanted to try and see
Upvotes: 0
Views: 43
Reputation: 1543
To make String.Join
work you will need to provide a collection of strings, not a custom type.
Ambiguity is due to covariance, since it can implicitly become an object
or string
in this case.
So instead of your approach go ahead with explicitly stating that it will be string
and pushing certain property of object
as that string
:
AllCubes = string.Join("|", Stuff.Select(x => x.Name));
.
This will provide an IEnumerable
of strings
which meets contract requirements IEnumerable<string>
.
Upvotes: 1