-1

How can I turn the model items into a one string in C#?

IEnumerable<MyModel> test = _table.entity.ToMyModel();

Now my model is like

return new myModel
{
    Item1 = "This is ",
    Item2 = " a test ",
    Item3 = " to make one sentence"
}

Now I want to do something like this to turn the first row of the IEnumerable into a sentence.

string xyz = test.First().toString(); 

I would like xyz to = "This is a test to make one sentence"

user1854438
  • 1,784
  • 6
  • 24
  • 30
  • See also related duplicates such as https://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object and https://stackoverflow.com/questions/4023462/how-do-i-automatically-display-all-properties-of-a-class-and-their-values-in-a-s – Peter Duniho Oct 05 '16 at 22:57

1 Answers1

0

This is one of the reason behind the ToString method being overridable.
You can simply override the ToString() inside your class' model and return whatever you like

public class myModel
{ 
   public string Item1 {get;set;}
   public string Item2 {get;set;}
   public string Item3 {get;set;}

   public override string ToString()
   {
       return string.Join(" ", this.Item1, this.Item2, this.Item3);
   }
}

....

myModel m = new myModel()
{
    Item1 = "This is",
    Item2 = "a test",
    Item3 = "to make one sentence"
};

Console.WriteLine(m.ToString());
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Is there any way of doing this without listing each item? – user1854438 Oct 05 '16 at 22:25
  • Using reflection, but this will be very expensive and probably not worth the effort being the items inside the model together with the ToString() override – Steve Oct 05 '16 at 22:26