简体   繁体   中英

Exclude range of IP addresses from datatable

I have a data table that includes a column holding IP addresses. I need to be able to filter the 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. (ie exclude 10.20.1.xxx, 10.20.2.xxx, ..., 10.20.14.xxx, 10.20.15.xxx and 10.20.61.xxx).

SQL

DELETE FROM sometable WHERE ip LIKE '10.20.1.%'

or

DELETE FROM sometable WHERE ip LIKE '10.20.%'

Linq

Without any code from you on how you're getting data from DB this will just get you a list of rows to be deleted, you can take it from there

var itemsToDelete = someList.Where(x => x.Ip.StartsWith("10.20.1"));

This worked for me:

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

I would do the following,

        DataTable dt; //your datatable here
        DataView dv = dt.DefaultView;
        foreach (DataRow dr in dt.Rows)
        {

            if (Regex.IsMatch(dr["Column name of your IP"].ToString(), "regex to check  IP") == false)
            {
               //Delete that row or something
            }
            else
            {
               //Do something else
            }
        }
        DataTable tempTable = dv.ToTable();
       //where temptable is your sorted and updated datatable

You can store this inside a method and call it to perform a check wherever you are binding or before that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM