简体   繁体   English

SqlParameter数组到对象

[英]SqlParameter array to object

SqlParameter[] _parameters = {                
     new SqlParameter( "@IDNumber", Person.IDNumber ),
     new SqlParameter( "@Name", Person.Name ),
     new SqlParameter( "@Surname", Person.Surname )
};

How to get the "Name" value from object array without using index? 如何在不使用索引的情况下从对象数组中获取“Name”值? What I want to do is, 我想做的是,

oPerson.Name = _parameters.Find(@Name).Value;

Use the following: 使用以下内容:

_parameters.Single(p => p.ParameterName == "@Name").Value;

This assumes one and only one instance of a SqlParameter with a given ParameterName exists. 这假设存在一个且只有一个具有给定ParameterNameSqlParameter实例。 If you're unsure if one exists, do the following: 如果您不确定是否存在,请执行以下操作:

var param = _parameters.SingleOrDefault(p => p.ParameterName == "@Name");
if (param != null) { oPerson.Name = param.Value; }

Using Linq, it is easy 使用Linq,很容易

string pName = "@Name";
var p = _parameters.FirstOrDefault(x => x.ParameterName == pName);
if(p != null) 
    oPerson.Name = p.Value.ToString();

I assume that you need this code because you are unsure about the presence or not of your parameter. 我假设您需要此代码,因为您不确定参数的存在与否。 So using FirstOrDefault allows to test for the result without using directly the Value property if your parameter doesn't exists in the collection 因此,如果集合中不存在参数,则使用FirstOrDefault可以在不直接使用Value属性的情况下测试结果

您可以使用First方法并通过其Name获取参数。

oPerson.Name = _parameters.First(x => x.ParameterName == "@Name").Value;

You could use Linq like in 你可以像使用Linq一样使用

oPerson.Name = _parameters.First( param => param.ParameterName.Equals("@Name")).Value;

to search for the value of "@Name" again. 再次搜索"@Name"的值。

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

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