如何根据另一个列表中的匹配项筛选列表?

时间:2012-07-24 12:53:57

标签: linq

我有一个组织对象

public class Organisation
{
    OrgId {get....}
    OrgName {get...}
    AccountTypes { get....} //this is of type List<AccountType>
}

和AccountType对象

public class AccountType
{
    AccountTypeId {get....}
    AccountTypeName {get...}
}

我正在寻找一种方法来查看现有的组织列表,并从另一个帐户类型列表中找不到帐户类型的每个组织中删除帐户类型(这将是从浏览器回发的邮件)。

我会做点什么吗?

var foundOrgs = from org in orgs
                where org.OrganisationId == Convert.ToInt32(hash["orgId"])
                select org;
Organisation organisation = foundOrgs.ElementAt(0);
organisation.AccountTypes.Clear();
organisation.AccountTypes = // What goes here?

我正在寻找一个Linq查询,它将一个列表与另一个列表进行比较,并仅返回AccountTypeID匹配或存在的项目。

2 个答案:

答案 0 :(得分:1)

您可以使用List<T>.RemoveAll

// where accounts is IEnumerable<int>
organisation.AccountTypes.RemoveAll(at => !accounts.Contains(at.AccountTypeId));

答案 1 :(得分:1)

编辑代码

//created account id list over here
var AccountTypeID = accountType.Select(x=>x. AccountTypeId);

//you code    
var foundOrgs = from org in orgs
                 where org.OrganisationId == Convert.ToInt32(hash["orgId"])
                 select org;
 Organisation organisation = foundOrgs.ElementAt(0);
 organisation.AccountTypes.Clear();
//changes in code where you want to change -// What goes here? 
List<AccountTypes> templist = organisation.AccountTypes;
 organisation.AccountTypes = 
               from acc in templist 
               where !AccountTypeID.Conains(acc.AccountTypeId)
                       select acc).ToList();

修改

不确定,但你可以尝试

var orgdata= from org in foundOrgs
        select { OrgId =org.OrgId ,OrgName = org.OrgName , 
                 AccountTypes  = ( from acc in org.AccountTypes
                                  where !AccountTypeID.Conains(acc.AccountTypeId)
                                  select acc) };

尝试这样的事情

var ids = {1, 2, 3};
  var query = from item in context.items
             where !ids.Contains( item.id )
             select item; 

这将为您提供不属于1,2,3,即ids列表的元素列表,同样可以在您的代码中应用,首先找出哪些不存在而不是从列表中删除

图像 enter image description here