简体   繁体   English

选择列表中的项目时如何将属性值设置为空

[英]How to set a property value to null when select items in a list

I have a class Like this,我有一个这样的课程,

class Test
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I want to select eligible items in List, I also want to set Name to null of the result list.我想在列表中选择符合条件的项目,我还想将结果列表的 Name 设置为 null。 I don't want to loop the collection again to set property value, is there a way to set the property value during the selection in linq?我不想再次循环集合来设置属性值,有没有办法在 linq 中的选择过程中设置属性值?

This is my current query:这是我当前的查询:

var v = from t in tests where ids.Contains(t.ID) select t;

Thanks谢谢

You can set it to null explicitly:您可以将其显式设置为null

var newTests = tests.Where(test => ids.Contains(test.ID))
                    .Select(test => { 
                                       test.Name = null; 
                                       return test;
                                    });

Or you can project new instances of Test :或者您可以投影Test新实例:

var newTests = tests.Where(test => ids.Contains(test.ID))
                    .Select(test => new Test { ID = test.ID });

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

相关问题 如何仅从某些属性设置为true的列表中选择项目 - How to only select items from a list with certain property set to true 抛出错误时如何为属性设置null值? - How to set a null value to a property when it throws an error? 将 ListBox DataSource 属性设置为 null 以更改列表项是否错误? - Is it wrong to set ListBox DataSource property to null in order to change list Items? 添加映射值时,属性设置为 null - Property set to null when mapped value is added 如何将列表项设置为null C#? - How to set list items to null C#? 如何使用反射将属性的值设置为null - How to set the value of a property to null using reflection 仅当该属性的当前值为null时,才可以设置EntityKey属性 - The EntityKey property can only be set when the current value of the property is null 只有当属性的当前值为null时,才能设置EntityKey属性 - The EntityKey property can only be set when the current value of the property is null 仅当该属性的当前值为null时,才可以设置EntityKey属性 - The EntityKey property can only be set when the current value of the property is null 如何在视图中使用选择列表将null值插入可为null的枚举属性? - How can I insert null value into a nullable enum property using a select list in a view?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM