How to add a new property to every list item in a list c #
I am new to C #. I have searched for this with no luck. Suppose the database result is converted to a list. Something like the following
var schedules = db.Schedules.Where(s => s.RequestId == id).ToList();
Now I need to add a new item to this list. Not a list item, but a property for every list item that exists in the list.
For example, in php, if its a multidimensional array, I can use foreach to loop through the array and just like $arrayList['new_key'] = "new_value";
How do I add a property like this to the list above schedules
in C #? More precisely; Schedule
is a dataset. And the new property is also what I want to retrieve from another property of another dataset.
Help rate.
Edit: Now I figured out what I really need. I need to make a left outer join to connect both Schedule and other model. I asked a new question: How to create a simple left outer join in a lambda expression in ASP.NET MVC5 EF
source to share
"Schedule" (or any returned set of objects) must contain the added property 1 . So either add a property to the object, or create a new object with the original object properties (plus one more) and select it. eg.
class Schedule2 : Schedule
{
public String NewProperty { get; set; }
public Schedule2(Schedule schedule)
{
// assign original properties here from "Schedule". e.g.
base.RequestId = schedule.RequestId;
}
}
Then:
var schedules = db.Schedules
.Where(x => x.RequestId == id)
.Select(x => new Schedule2(x))
.ToList();
1Despite DynamicObject
, but I do not think it is appropriate in this case.
source to share
You said it Schedule
is a dataset. I am assuming it Schedule
is an instance System.Data.DataSet
with a separate table or System.Data.DataTable
directly.
It is very easy to add additional property to DataTable
. All you need to do beforehand is create and add a new one DataColumn
to the property Columns
for DataTable
. Something like that:
DataSet ds1 = <whatever method returns the dataset>
DataTable dt1 = ds1.Tables[0];
dt1.Columns.Add("NewCol", typeof(string));
You should now be able to use "NewCol" as an indexer on any DataRow
of dt1
:
dt1.Rows[0]["NewCol"] = "a simple string";
source to share