使用包含运算符的LINQ加入两个集合

时间:2017-11-17 10:43:09

标签: c# linq collections

我有以下两个课程

Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type

我想根据评论中给出的标准设置C.Type基础

我试过了,但它不能正常工作

 var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();

4 个答案:

答案 0 :(得分:2)

这很简单,也很迭代,可能有更好的解决方案。但它会做你需要的。

public void SetTypeOnCList(List<D> dlist, List<C> clist)
{
    clist.ForEach(c =>
    {
        var dobj = dlist.FirstOrDefault(d => d.CIds.Contains(c.Id));
        if (dobj != null)
        {
            c.Type = dobj.Type;
        }
    });
}

答案 1 :(得分:1)

试试此代码

public IQueryable GetData(string DataType) {

 IQueryable<DatabaseObject> dbData = (
    from t in db.All<DatabaseObject>().Where(e => e.Category == TransType)
    join e in WebHelpers.LocalList
    on t.Type equals e.Type
    orderby t.DateOccurred descending
    select t
); 

return dbData;

}

答案 2 :(得分:1)

如果连接条件是另一个集合上的Enumerable.Join,则可以使用Contains。您可以首先在SelectMany - 集合中使用fromfrom ... Guid查询语法):

var allDIDs = from d in D_Collection from id in d.CIds select new { dObj = d, id };
var cToUpdate = from c in C_Collection
                join dID in allDIDs
                on c.Id equals dID.id
                select new { cObj = c, dType = dID.dObj.Type };

foreach (var x in cToUpdate.Distinct())
    x.cObj.Type = x.dType;

或使用此查询:

var cToUpdate = C_Collection
    .Select(c => new { 
        cObj = c, 
        FirstmatchingIdType = D_Collection
          .FirstOrDefault(d => d.CIds.Contains(c.Id))?.Type 
     })
    .Where(x => x.FirstmatchingIdType != null);

foreach(var x in cToUpdate)
    x.cObj.Type = x.FirstmatchingIdType;

答案 3 :(得分:1)

我认为这样做会更简单:

var c_comparisons = D_Collection.SelectMany(x => x.CIds.Select(y => new C { Id = y, Type = x.Type }));

foreach (var comparison in c_comparisons)
{
    var c = C_Collection.FirstOrDefault(x => x.Id == comparison.Id);

    if (c != null)
    {
        c.Type = comparison.Type;
    }
}