简体   繁体   English

在IEnumerable对象中插入列表

[英]Inserting a list in an IEnumerable of objects

I have a IEnumerable 'myobjects' where myModel structure is as follows.. 我有一个IEnumerable'myobjects',其中myModel结构如下。

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). 在上面的IEnumerable中,我有一个myModel(让我们说SchemaName'abc'和PropertyName'xyz'),其中optionvalues为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. 我有一个列表“ mylist”,其中包含需要在上述IEnumerable中插入的值以代替空optionvalues的值。

I would appreciate if someone could guide me how to insert mylist in myobjects where SchemaName is 'abc' and PropertyName is 'xyz' . 如果有人可以指导我如何在SchemaName为'abc'和PropertyName为'xyz'的myobjects中插入mylist,我将不胜感激。

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. 请注意,在此实现中,所有对象都将引用同一列表,如果更改mylist中的某些内容,它将应用于使用该对象的所有对象。

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: 假设在具有该模式名称和属性名称的myobjects中只有一个值(或者您只想添加第一个出现的值),您可以这样操作:

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 或者,使用WhereForEach

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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