c# - Add hyphen or underscore between two int -
i trying id's database. if 1 value works expected want method return more 1 value. example
if, id1 = 1 , id2 = 2
want display 1-2
or 1_2
. can't seem figure out how put hyphen -
or underscore _
between 2 int
. code below
public int getid() { using (sqlconnection connection = new sqlconnection(connectionstring)) { string username = httpcontext.current.user.identity.name; userinfo info = new userinfo(); using (sqlcommand cmd = new sqlcommand("select firstid, secondid mytable username=@username")) { cmd.parameters.addwithvalue("username", username); cmd.connection = connection; connection.open(); using (sqldatareader reader = cmd.executereader()) { while (reader.read()) { info.firstid = reader.getint32(0); info.secondid = reader.getint32(1); } } } return info.firstid + "_" + info.secondid; } }
my userinfo
class has basic get , set
properties. have come across tuple
today. i've tried using tuple
values displayed (1,2)
. tuple
of course can add underscore _
or hyphen -
problem can't rid of brackets ()
and comma ,
separates values. can please point me in right direction. in advance , support.
the method claims return int
:
public int getid()
but sort of attempts return string
:
return info.firstid + "_" + info.secondid;
a hyphen or underscore means it's no longer numeric data type, it's string. you'd have return string:
public string getid() { // etc. return string.format("{0}_{1}", info.firstid, info.secondid); }
if want data still structured in way, suggest tuple<int, int>
trick:
public tuple<int, int> getid() { // etc. return new tuple<int, int>(info.firstid, info.secondid); }
then consuming code decide how display it:
var id = getid(); console.write(string.format("{0}_{1}", id.item1, id.item2));
this means you'd using unintuitive names item1
, item2
. if want more aptly named, can introduce custom object:
public class ids { public int firstid { get; set; } public int secondid { get; set; } }
then return instance of that. approach has added advantages:
- you can rename
firstid
,secondid
more meaningful names - you can make object immutable making setters
private
, adding constructor accepts values - you can override
.tostring()
give defaultstring
representation underscore
for example:
public class ids { public int firstid { get; private set; } public int secondid { get; private set; } private ids() { } public ids(int firstid, int secondid) { firstid = firstid; secondid = secondid; } public override string tostring() { return string.format("{0}_{1}", firstid, secondid); } }
then return instance of that:
public ids getid() { // etc. return new ids(info.firstid, info.secondid); }
and consuming code can display as-is, since string representation internally defined:
var id = getid(); console.write(id);
Comments
Post a Comment