开发者

How to write LINQ to convert datatypes and to concatenate strings?

I am new to LINQ, and I wish to convert from one datatype to another in C#, as well as con开发者_运维问答catenate a string. How would I accomplish this?

For example, what would the SQL statement

SELECT IPv4 = CONVERT(varchar(3), IPv4_octet1) + '.' +
              CONVERT(varchar(3), IPv4_octet2) + '.' +
              CONVERT(varchar(3), IPv4_octet3) + '.' +
              CONVERT(varchar(3), IPv4_octet4) FROM table;

be in LINQ? (The IPv4_octet's are stored as tinyints in the SQL table.)


In this case I suspect you could just write:

var query = data.Select(x => x.IpV4Octet1 + "." + 
                             x.IpV4Octet2 + "." + 
                             x.IpV4Octet3 + "." + 
                             x.IpV4Octet4);

More generally you'd call ToString, e.g.:

// You wouldn't want to actually do this, but...
var query = data.Select(x => x.IpV4Octet1.ToString() + x.IpV4Octet4.ToString());

If you want more control, and you're not using the result in the rest of the query, you may well want to do the formatting on the .NET side - simply use AsEnumerable when you've selected all the information you want from the database, and then do the rest in LINQ to Objects. For example:

var query = db.Select(x => new { x.HostName, x.IpV4Octet1, x.IpV4Octet2,
                                 x.IpV4Octet3, IpV4Octet4 })
              .AsEnumerable() // Switch to LINQ to Objects for rest of query
              .Select(x => new { x.HostName,
                                 Address = string.Format("{0}.{1}.{2}.{3}"),
                                                         x.IpV4Octet1,
                                                         x.IpV4Octet2,
                                                         x.IpV4Octet3,
                                                         x.IpV4Octet4) });


try this:

string ipv4 = string.Join('.',octets.Select(o => o.ToString()).ToArray());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜