Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlParameter array to object

Tags:

arrays

c#

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? What I want to do is,

oPerson.Name = _parameters.Find(@Name).Value;
like image 523
Cute Bear Avatar asked Aug 30 '26 13:08

Cute Bear


2 Answers

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. 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; }
like image 198
decPL Avatar answered Sep 02 '26 02:09

decPL


Using Linq, it is easy

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

like image 42
Steve Avatar answered Sep 02 '26 02:09

Steve