Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add object to a BindingList in a BindingList

Tags:

c#

list

linq

I have a bindinglist of activity, and each activity has a bindinglist of BuyOrders

bindingListActivty.Select(k => k._dataGridViewId == 1);

If I understand correctly, i can select the activity, but I cannot access any method inside the activity. How do I access the method without creating a new instance of a bindinglist ?

I tought this would work, but no

bindingListActivty.Select(k => k._dataGridViewId == 1).addBuyOrders(new BuyOrders());
like image 213
Insecurefarm Avatar asked Sep 24 '14 13:09

Insecurefarm


3 Answers

Select returns an IEnumerable<T>, which will not have your addBuyOrders method. You need to either use a foreach or you could use FirstOrDefault with a Where clause to get the individual object that exposes the method.

For example:

foreach:

var activities = bindingListActivty.Select(k => k._dataGridViewId == 1);
foreach(var a in activities)
{
    a.addBuyOrders(new BuyOrders());
}

FirstOrDefault (this likely makes more sense based on your where clause):

var activity = bindingListActivty.Where(k => k._dataGridViewId == 1).FirstOrDefault();
if (activity != null)
{
    activity.addBuyOrders(new BuyOrders());
}
like image 165
Jason Down Avatar answered Nov 08 '22 00:11

Jason Down


You could try this one:

// Get the activity from bindingListActivity, whose k._dataGridViewId is equal to 1.
var activity = bindingListActivty.SingleOrDefault(k => k._dataGridViewId == 1);

// If the activity has been found and the a new BuyOrders object.
if(activity!=null)
    activity.addBuyOrders(new BuyOrders());
like image 33
Christos Avatar answered Nov 08 '22 00:11

Christos


It is important for you to understand that IEnumerable<T>.Select() is not for querying. You need to use Where(), First() or FirstOrDefault() for any queries. Select() is a projection of each element. This means you are performing a transformation from T1 -> T2. You have made a projection of each activity on a boolean value (k._dataGridViewId == 1). The result type of

bindingListActivty.Select(k => k._dataGridViewId == 1);

is

IEnumerable<bool>
like image 2
Sebastian Avatar answered Nov 08 '22 00:11

Sebastian