Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat the fields in one Property

Tags:

c#

asp.net

linq

I have list of properties. like

public string name {get;set;}
public string lastname {get;set;}
public string age {get;set;}
public string fullName {get;set;}

Now what I want to do is concat the first 3 properties in the last 'FullName' property.

Means if I have name = John, Lastname = smith, age = 20

then

Fullname should be John Smith 20

How can I do that. Should I do that in Domain Class with the help of setter property or Can I do that with using Linq.

I have more than 1000 records which is brought in IEnumerable . How can I do that. I want to avoid looping the records.

like image 377
Moiz Avatar asked Oct 17 '25 13:10

Moiz


2 Answers

I would make it a read-only property instead - unless you want to start having to parse the value into bits when it's set. So:

public string FullName
{
    // This is assuming you've also fixed the property names to be conventional
    // I'd also suggest changing "Name" to "GivenName" or "FirstName".
    get { return string.Format("{0} {1} {2}", Name, LastName, Age); }
}

If you really want to have a setter, I would suggest splitting the input by spaces and then setting each of the three other properties. Don't have separate storage for the FullName property (an independent field) as otherwise the data can become inconsistent.

like image 130
Jon Skeet Avatar answered Oct 19 '25 03:10

Jon Skeet


public string FullName
{
    get 
    { 
        return name + " " + lastname + " " + age.ToString();
    }
}

Or

public string FullName
{
    get 
    { 
        return string.Format("{0} {1} {2}", name, lastname, age);
    }
}
like image 32
Vivek Jain Avatar answered Oct 19 '25 05:10

Vivek Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!