Bill Lock
Bill Lock

Reputation: 61

How do I use LINQ to filter a datatable against a Lst of strings that need to be split?

I have a datatable and I want to use LINQ to filter against a List of strings, with each string delimited using the pipe ('|'), and contains two values. The list (List Actions) of string looks like this. This is only two strings in this list, but it can have many more.

    8/1/2013 9:57:52 PM|Login for [email protected]
    8/1/2013 9:57:37 PM|Login for [email protected]

The datatable has five (5) fields in each row, and I'm using each string from the list above to compare two fields (Text and Time) in the datatable to omit or delete those rows. The datatable is structured like this

    DataTable stdTable = new DataTable("Actions");
    DataColumn col1 = new DataColumn("Area");
    DataColumn col2 = new DataColumn("Action");
    DataColumn col3 = new DataColumn("Time");
    DataColumn col4 = new DataColumn("Text");

Currently I'm manually performing all this, but I know it can be done in LINQ with just a few lines of code. I'm not sure how to iterate thru the list and use the split. I saw this example, but the split is beyond me.

    // Get all checked id's.
    var ids = chkGodownlst.Items.OfType<ListItem>()
    .Where(cBox => cBox.Selected)
    .Select(cBox => cBox.Value)
    .ToList();

    // Now get all the rows that has a CountryID in the selected id's list.
    var a = dt.AsEnumerable().Where(r => 
    ids.Any(id => id == r.Field<int>("CountryID"))
    );

    // Create a new table.
    DataTable newTable = a.CopyToDataTable();

Any help would be appreciated.

Thanks

Upvotes: 2

Views: 1604

Answers (1)

King King
King King

Reputation: 63347

List<string> list = {
                       "8/1/2013 9:57:52 PM|Login for [email protected]",
                       "8/1/2013 9:57:37 PM|Login for [email protected]"
                    };
var a = dt.AsEnumerable().Where(x=>
              !list.Select(y=> new {
                                    Time =  DateTime.Parse(y.Split('|')[0]),
                                    Text = y.Split('|')[1]
                                  })
                  .Any(z=> z.Time == x.Time && z.Text == x.Text));

or

var a = dt.AsEnumerable().Where(x=>
                    !list.Any(y=> y == string.Format("{0}|{1}",x["Time"],x["Text"])));

DataTable newTable = a.CopyToDataTable();

Upvotes: 2

Related Questions