Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate All Properties to a String with LINQ

Tags:

c#

linq

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.

like image 821
notlkk Avatar asked Feb 09 '17 23:02

notlkk


2 Answers

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)
like image 107
Sergey Berezovskiy Avatar answered Oct 14 '22 00:10

Sergey Berezovskiy


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 } )
             ));
like image 34
CodingYoshi Avatar answered Oct 13 '22 22:10

CodingYoshi