Home > OS >  Compare Two List and return Data from first list based on Ids in Linq C#
Compare Two List and return Data from first list based on Ids in Linq C#

Time:06-17

var solutionItems = solutionInfoResponse
  .Items
  .Where(x => solutionInfoResponse
     .ProductGroup
     .FirstOrDefault(p => productGroupIds.Contains(p.GroupId))
     .Items
     .Any(it => it.Id == x.ItemId))
  .ToList();

Here I am getting List of FirstProduct group only with exist in ProductGroupsIds, so I want all product group with existing same condition. Please Help me.

Here

 public class ProductGroup
    {
        public string GroupId { get; set; }
        public List<ProductGroupItem> Items { get; set; }

    }

and

  public class ProductGroupItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
       
    }

and

public class SolutionItem
{
    public string ItemId { get; set; }

}

Finally

   public class SolutionInfoResponse
    {
        public List<SolutionItem> Items { get; set; }
        public SolutionInfo SolutionInfo { get; set; }
        public List<ProductGroup> ProductGroup { get; set; }
    }

CodePudding user response:

If it's possible that the same item can be in several groups we should not use FirstOrDefault but Where. We obtain all such groups and then check if there's any groupItem with required Id:

var solutionItems = solutionInfoResponse
  .Items
  .Where(item => solutionInfoResponse
     .Groups
     .Where(group => productGroupIds.Contains(group.GroupId))
     .SelectMany(group => group.Items)
     .Any(groupItem => groupItem.Id == item.Id))
  .ToList();
  • Related