Linq not in select on datatable

前端 未结 3 553
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 06:02

Hi i\'ve got 2 data tables (bannedlist,countrylist), both contains list of country names and cods in columns cc and country. I am trying to do a query where i can select cou

相关标签:
3条回答
  • 2021-01-01 06:16

    You can use the Except() LINQ extension method like this:

    var result = full.Except(banned);
    

    However this will work fine with the default comparer of the contained type. Thus if you want to use a specific column like in your example, you might need another approach like:

    from r in ccList
    where !bannedCCList.Any(b => b["cc"] == r["cc"])
    select r;
    

    Using Except() implies the references are the same in both collections, which I think is not the case with Tables, or correct me if I'm wrong.

    0 讨论(0)
  • 2021-01-01 06:30

    Except would work if you use it on sequences of the countries:

    using System.Linq;
    ...
    
        var ccList = from c in ds.Tables[2].AsEnumerable()
                     select c.Field<string>("Country"); 
        var bannedCCList = from c in ds.Tables[1].AsEnumerable()
                           select c.Field<string>("Country");
        var exceptBanned = ccList.Except(bannedCCList);
    

    If you need the full rows where the countries aren't banned, you could try a left outer join:

        var ccList = ds.Tables[2].AsEnumerable();
        var bannedCCList = ds.Tables[1].AsEnumerable();
        var exceptBanned = from c in ccList
                           join b in bannedCCList
                             on c.Field<string>("Country") equals b.Field<string>("Country") into j
                           from x in j.DefaultIfEmpty()
                           where x == null
                           select c;
    
    0 讨论(0)
  • 2021-01-01 06:41

    Try this:

    var query = ccList.Except(bannedCCList);
    
    0 讨论(0)
提交回复
热议问题