[ASP.NET] LINQ 牛刀小试
作者:互联网
[ASP.NET] LINQ 牛刀小试
先感谢点部落上次的赠书活动,赠了LINQ的书,
再看的过程中我想到以前遇到的一个考题,
有ABCD四台Server分别给他们的连线速度和是否可连接,
要如何去判断哪台可以连接而且速度最快?(不能使用数据库)
A可连线,连线速度为15kbps,B可连线,连线速度为30kbps,
C不可连线,连线速度为40kbps,D可连线,连线速度为10kbps,
然后有两个函数一个是get_speed(Server Name)可取得Server的速度
connect(Server Name)可取得Server是否可连接,
我之前的方法是用二维数组来存,先判断Server是否连接,
然后用Bubble Sort来排序由大到小取第一个(因为写Bubble Sort比较简单),
写了一堆才解决这个问题,可是用LINQ却可以轻松解决(写不好请多包涵),
首先写一个简单的对象,有Server名称、Server速度和Server可否连接这些属性,
然后把get_speed()和connect()写成对象的方法,
public class objServer
{
private object _ServerName;
private object _ServerSpeed;
private object _ServerConnect;
public object ServerName
{
get
{
return _ServerName;
}
set
{
_ServerName = value;
}
}
public object ServerSpeed
{
get
{
return _ServerSpeed;
}
set
{
_ServerSpeed = value;
}
}
public object ServerConnect
{
get
{
return _ServerConnect;
}
set
{
_ServerConnect = value;
}
}
public int get_speed()
{
return Convert.ToInt16(ServerSpeed);
}
public bool connect()
{
return Convert.ToBoolean(ServerConnect);
}
}
接下来建立ABCD这4台Server,然后把这四个对象丢到List里面,
把对象放入List或是Array不是什么新鲜事,
但是用对象的属性或方法来对对象排序,就真的蛮酷的,
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Linq;
public partial class exam4 : System.Web.UI.Page
{
private objServer _A;
private objServer _B;
private objServer _C;
private objServer _D;
public objServer A
{
get
{
_A = new objServer();
_A.ServerName = "A";
_A.ServerSpeed = 15;
_A.ServerConnect = true;
return _A;
}
}
public objServer B
{
get
{
_B = new objServer();
_B.ServerName = "B";
_B.ServerSpeed = 30;
_B.ServerConnect = true;
return _B;
}
}
public objServer C
{
get
{
_C = new objServer();
_C.ServerName = "C";
_C.ServerSpeed = 40;
_C.ServerConnect = false;
return _C;
}
}
public objServer D
{
get
{
_D = new objServer();
_D.ServerName = "D";
_D.ServerSpeed = 10;
_D.ServerConnect = true;
return _D;
}
}
protected void Page_Load(object sender, EventArgs e)
{
List Server = new List { A, B, C, D };
IEnumerable enumServer =
from myServer in Server
where myServer.connect() == true
orderby myServer.get_speed() descending
select myServer;
objServer CorrectServer = enumServer.First();
this.Response.Write("ServerName:"+ CorrectServer.ServerName.ToString() + ", Speed:" + CorrectServer.ServerSpeed.ToString() + "Kbps");
}
}
像我是用IEnumerable来实践在Where的条件式用myServer.connect() == true来筛选可连接的,
然后再orderby来排序由大到小,依造对象的方法来筛选和排序对象,真的很方便
最后再选出已经筛选和排序好的第一个对象,就像是SQL里面的Top 1,
这样就可以轻松的解决这个问题,END…
标签:ASP,牛刀小试,get,System,objServer,using,NET,Server,public 来源: https://www.cnblogs.com/petewell/p/11489936.html