I have a class like this:
public class MyClass
{
public int Line;
public string Name1;
public string Name2;
}
and a collection of MyClass objects:
List<MyClass> myObjs = myService.GetObjects();
where myObjs
has 2 elements:
[0]: Line: 1, Name1: "Test1", Name2: "Test2"
[1]: Line: 2, Name1: "Test3", Name2: "Test4"
I'd like to get every object with their properties concatenated in a string like:
"1,Test1,Test2;2,Test3,Test4"
I tried string.Join(",", myObjs.Select(x => x.Line));
but that only gives me a list of all the Line values. I need everything in the object.
If it's OK to list fields manually:
String.Join(";", myObjs.Select(x => $"{x.Line},{x.Name1},{x.Name2}"))
If not, but all fields are non-collections, generics or indexers
var fields = typeof(MyClass).GetFields();
var result = String.Join(";", myObjs.Select(x =>
String.Join(",", fields.Select(f => f.GetValue(x)))
));
NOTE: If your class actually have properties instead of fields, you should use GetProperties()
instead of GetFields()
.
And last option, if it's OK to override ToString()
method of your class:
public override string ToString() => $"{Line},{Name1},{Name2}";
And converting list of such objects will look like
String.Join(";", myObjs)
This will get your object's fields separated by commas:
myObjs.Select( x =>
String.Join( ",", new [] { x.Line.ToString(), x.Name1, x.Name2 } ));
Here is the full answer which will separate each object with semi-colons and use the above code:
var result = string.Join(";", myObjs.Select( x =>
String.Join( ",", new [] { x.Line.ToString(), x.Name1, x.Name2 } )
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With