Linq没有选择数据表
您好我有2个数据表(禁止列表,国家列表),两个都包含国家名称和鳕鱼列表cc和国家。 我正在尝试进行查询,我可以从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(); CountryListBox.DataSource = boundTable; CountryListBox.DataValueField = "cc"; CountryListBox.DataTextField = "country"; CountryListBox.DataBind(); }
如果您在国家/地区的序列中使用它,则会起作用:
using System.Linq; ... var ccList = from c in ds.Tables[2].AsEnumerable() select c.Field("Country"); var bannedCCList = from c in ds.Tables[1].AsEnumerable() select c.Field ("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("Country") equals b.Field ("Country") into j from x in j.DefaultIfEmpty() where x == null select c;
您可以使用Except()LINQ扩展方法,如下所示:
var result = full.Except(banned);
但是,这将适用于包含类型的默认比较器。 因此,如果您想使用示例中的特定列,则可能需要另一种方法,例如:
from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"]) select r;
使用Except()意味着两个集合中的引用都是相同的,我认为不是表格的情况,或者如果我错了就纠正我。
试试这个:
var query = ccList.Except(bannedCCList);