Linq没有选择数据表

时间:2009-07-22 11:55:47

标签: c# linq datatable

您好我有2个数据表(禁止列表,国家/地区列表),两个数据表都包含国家/地区名称和鳕鱼列表。我正在尝试进行查询,我可以从countrylist表中选择不在bannedlist表中的国家,以便创建第3个表。

有什么想法吗?

我对此并不太了解。

        var ccList = ds.Tables[2].AsEnumerable(); 
        var bannedCCList = ds.Tables[1].AsEnumerable();
        var query = from r in ccList....

...

尝试后

var bannedCCList = ds.Tables[1].AsEnumerable();
    var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r;

我仍然获得相同的国家/地区列表。被禁止的人没有被删除。这里有更多细节,以便解释更多。不确定我做错了什么

 protected void BindCountryBan(string subd)
{
    DataSet ds = new DataSet();
    ds = new DB().CountryBan_GetSiteSettings();

        BannedCountryListBox.DataSource = ds.Tables[1];
        BannedCountryListBox.DataValueField = "cc";
        BannedCountryListBox.DataTextField = "country";
        BannedCountryListBox.DataBind();

//bind country list
    var ccList = ds.Tables[2].AsEnumerable(); 
    var bannedCCList = ds.Tables[1].AsEnumerable();
    var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r;
    //var query = ccList.Except(bannedCCList); 




    //CountryListBox.DataSource = ds.Tables[2];
    DataTable boundTable = query.CopyToDataTable<DataRow>();
    CountryListBox.DataSource = boundTable;
    CountryListBox.DataValueField = "cc";
    CountryListBox.DataTextField = "country";
    CountryListBox.DataBind();
}

3 个答案:

答案 0 :(得分:7)

除非在国家/地区的序列中使用它,否则会起作用:

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);

如果您需要未禁止国家/地区的完整行,则可以尝试左外连接:

    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;

答案 1 :(得分:5)

您可以使用Except()LINQ扩展方法,如下所示:

var result = full.Except(banned);

但是,对于包含类型的默认比较器,这将正常工作。因此,如果您想使用示例中的特定列,则可能需要另一种方法,如:

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

使用Except()意味着两个集合中的引用都是相同的,我认为不是表格的情况,或者如果我错了就纠正我。

答案 2 :(得分:2)

试试这个:

var query = ccList.Except(bannedCCList);
相关问题