2014年7月13日 星期日

[RESOLVED] Exclude range of IP addresses from datatable


I am displaying data in a grid that contains a coulmn to display IP addresses. I use a data table to bind the grid. User can select to exclude a facility and the facility is identified by a range of IP addresses.


I need to be able to filter data table rows and remove all rows where IP address is in the range of, say, from 10.20.1.xxx to 10.20.15.xxx as well as 10.20.61.xxx. (i.e. exclude 10.20.1.xxx, 10.20.2.xxx, 10.20.3.xxx, ..., 10.20.14.xxx, 10.20.15.xxx and 10.20.61.xxx).





NoBullMan


I need to be able to filter data table rows and remove all rows where IP address is in the range


Where are you trying to achieve ;


at backend : can use not like or not in operator;


or


at code level use LINQ or Datatable Expression 



I want to do this at BLL level, not in database query. Can you tell me how I can use Linq, or data table select, or regex to achieve this?



Hi,


You could simple try below method:






DataTable table = new DataTable();
DataTable Newtable = new DataTable();
table.Columns.Add("IP", typeof(string));

table.Rows.Add("10.20.1.1");
table.Rows.Add("10.20.3.1");
table.Rows.Add("10.20.11.1");
table.Rows.Add("10.20.14.1");
table.Rows.Add("10.20.15.1");
table.Rows.Add("10.20.16.1");
table.Rows.Add("10.20.61.1");

Newtable = (from r in table.AsEnumerable()
where ( Convert.ToInt32(r.Field("IP").Split('.')[2]) > 15 && Convert.ToInt32(r.Field("IP").Split('.')[2]) != 61)
select r).CopyToDataTable();
GridView1.DataSource = Newtable;
GridView1.DataBind();

Regards



Thank you Shawn. How do I enforce the first two octets be 10.20?


Would this work:


Newtable = (from r in table.AsEnumerable()
where (
Convert.ToInt32(r.Field("IP").Split('.')[0]) == 10 &&
Convert.ToInt32(r.Field("IP").Split('.')[1]) == 20 &&
Convert.ToInt32(r.Field("IP").Split('.')[2]) > 15 &&
Convert.ToInt32(r.Field("IP").Split('.')[2]) != 61)
select r).CopyToDataTable();

An IP like 20.40.1.xxx should not be excluded whereas 10.20.1.xxx should be.



Shawn,


if the data table has a row that contains no IP, the statement throws an null exception. How can I check IP field actually contains any data before attempting to access it and "Split" it?


I want to leave the rows that have no IP alone (don't exclude them).


Thank you.


沒有留言:

張貼留言