Reputation: 1231
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.
Upvotes: 5
Views: 6926
Reputation: 95
This is the more generic way for list if anyone needs,
private string GetConcatedString<T>(List<T> listItems, char delimiter)
{
var fields = Type.GetType(listItems.GetType().GetGenericArguments()[0].FullName).GetProperties();
return string.Join("", listItems.Select(x =>
string.Join(delimiter, fields.Select(f => f.GetValue(x))).TrimEnd(delimiter)));
}
Upvotes: 0
Reputation: 27009
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 } )
));
Upvotes: 1
Reputation: 236228
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)
Upvotes: 14