简体   繁体   中英

Inserting a list in an IEnumerable of objects

I have a IEnumerable 'myobjects' where myModel structure is as follows..

public class myModel
    {
        public string SchemaName { get; set; }
        public string PropertyName { get; set; }
        public List<string> optionvalues { get; set; }
    }

In the above IEnumerable I have one myModel (lets say with SchemaName 'abc' and PropertyName 'xyz') where optionvalues is null(count=0).

I have a List 'mylist' which contains the values which needs to be inserted in the above IEnumerable in place of null optionvalues.

I would appreciate if someone could guide me how to insert mylist in myobjects where SchemaName is 'abc' and PropertyName is 'xyz' .

Thanks

var filtered = myobjects.Where(o=>o.SchemaName =="abc" && o.PropertyName == "xyz" && o.optionvalues==null);
foreach (var obj in filtered)
{
   obj.optionvalues=mylist;
}

note that in this implementation all your object will reference the same list, if you change something in mylist it will apply to all the objects using it.

Assuming there is only single value (or you only want to add in the first occurred value) in myobjects which have that that schema name and property name You could do it this way:

var obj = myobjects.Single(x => 
    x.SchemaName =="abc" && x.PropertyName == "xyz" && (x.optionvalues == null || x.optionvalues.Count == 0));
obj.optionvalues = mylist;

or

var obj = myobjects.First(x => 
    x.SchemaName =="abc" && x.PropertyName == "xyz" && (x.optionvalues == null || x.optionvalues.Count == 0));
obj.optionvalues = mylist;

Alternatively, use Where and probably ForEach

var objcoll = myobjects.Where(x => 
    x.SchemaName =="abc" && x.PropertyName == "xyz" && (x.optionvalues == null || x.optionvalues.Count == 0)).ToList();
objcoll.ForEach(x => x.optionvalues = mylist);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM