I have an object like that
public class MyModel
{
public int Key { get; set; }
public string Value { get; set; }
}
And I have model
like List<MyModel>
model[0]=new MyModel(){Key = 1,Value ="Something"};
model[1]=new MyModel(){Key = 3,Value ="Something else"};
I want this output:
1. Value is = Something //there is \n here
3. Value is = Something else
So the seperator is \n
and while string.join(" \n ", ? )
what should I do?
Is that possible or not? I did it like that but I want to learn can I string.join()
do that:
var newArray = model.Select(x => ((x.Key)+". Value is ="+x.Value));
string.join(" \n ",newArray );
Sorry for my bad english...
var modelList = new List<MyModel>(){
new MyModel(){ Key = 1, Value = "Value 1"},
new MyModel(){ Key = 3, Value = "Value 2 with Key3"}
};
var stringArray = modelList.Select(model=> $"{model.Key}. Value={model.Value}");
var finalString = String.Join('\n', stringArray);
Console.Write(finalString);
You did well. There are other ways but they are no more correct (in some cases at least).
Example with custom ToString method:
var all = string.Join("\n", model);
public class MyModel
{
public int Key { get; set; }
public string Value { get; set; }
public override string ToString() => $"{Key}. Value Is: {Value}";
}
Or directly with project array:
var all = string.Concat(model.Select(x => $"{x.Key}. Value Is: {x.Value}\n"));
but there's an unnecessary line brake at the end.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.