2

我的系统中有两个类似的对象。

  • LeadImportViewModel
  • LeadGridViewModel

我需要QtyDuplicates在我的LeadImportViewModel集合中填充该字段,该字段应显示 LeadGridViewModel 集合中 CompanyNameStripped值相同的相应记录的数量。

public class LeadImportViewModel
{
    public int Id { get; set; }
    public string CompanyName { get; set; }
    public string CompanyNameStripped { get; set; }
    public int QtyDuplicates{ get; set; }
}

public class LeadGridViewModel
{
    public int LeadId { get; set; }
    public string CompanyName { get; set; }
    public string CompanyNameStripped { get; set; }
}

集合创建如下:

var coll = (from t1 in db.Leads_Staging
                    select new LeadImportViewModel
                        {
                            Id = t1.Id,
                            CompanyName = t1.CompanyName,
                            CompanyNameStripped = t1.CompanyNameStripped,

                        });

使用 LINQ/C# 最有效的方法是什么?

4

4 回答 4

1

听起来你只需要:

var count = leadImports.Select(x => x.CompanyNameStripped))
                       .Intersect(leadGrids.Select(x => x.CompanyNameStripped)))
                       .Count();

或者:

var names = new HashSet<string>(leadImports.Select(x => x.CompanyNameStripped));
var count = leadGrids.Count(x => names.Contains(x.CompanyNameStripped));
于 2012-11-06T19:18:36.407 回答
1

使用ForEachCount方法:

List<LeadImportViewModel> leadImportViewModelList = new List<LeadImportViewModel>();
List<LeadGridViewModel> leadGridViewModelList = new List<LeadGridViewModel>();

leadImportViewModelList.ForEach(vm => vm.QtyDuplicates 
    = leadGridViewModelList.Count(
    gv => gv.CompanyNameStripped = vm.CompanyNameStripped));
于 2012-11-06T19:18:59.990 回答
1

list.Select(a => a.CompanyNameStripped).Intersect(list2.Select(b => b.CompanyNameStripped).Count()

于 2012-11-06T19:21:55.927 回答
0

尝试

var coll = (from t1 in db.Leads_Staging
                select new LeadImportViewModel
                    {
                        Id = t1.Id,
                        CompanyName = t1.CompanyName,
                        CompanyNameStripped = t1.CompanyNameStripped,
                        QtyDuplicates = db.LeadGridViewModel.Count(
                                        gv => gv.CompanyNameStripped == t1.CompanyNameStripped)
                    });
于 2012-11-07T12:00:03.650 回答