无法使用linq

时间:2015-07-04 02:49:58

标签: linq

我有一个名为objCustomerData的全局变量列表 我希望能够在GetBranch方法中返回不同的数据。

这没有发生。它返回所有重复项。我想要它 只返回不同的分支。

请问我在这里做错了什么?

        private List<Customer> objCustomerData;

        public ActionResult Index()
        {
            InventoryAssViewModel objModel = new InventoryAssViewModel();
            try
            {   
                 if (countryValue == "CA")
                {
                    objCustomerData = _inventoryService.GetListCountryData("CAA");

                    objModel.BranchModel = GetBranch();
                }
                else 
                {
                    objCustomerData = _inventoryService.GetListCountryData("NIG");                 
                }
            }
            catch (Exception ex)
            {

            }

            return View(objModel);
        }


        public List<Branch> GetBranch()
        {
            List<Branch> filterBranch;

            try
            {
                filterBranch = (from c in objCustomerData
                    select new Branch()
                    {
                        Id = c.Branch,
                        BranchName = c.Branch
                    }).Distinct().ToList();
            }
            catch (Exception)
            {               
                throw;
            }
            return filterBranch;
        }

2 个答案:

答案 0 :(得分:1)

试试这个,

filterBranch = objCustomerData.Select(c => c.Branch).Distinct().Select(c => new Branch()
{
    Id = c,
    BranchName = c
})).ToList();

或者

filterBranch = objCustomerData.GroupBy(x => x.Branch).Select(c => new Branch()
{
    Id = c.Key,
    BranchName = c.Key
})).ToList();

答案 1 :(得分:0)

您必须在IEquatable<T>类上实现Branch,或者假设Branch.Branch是一个字符串,您可以利用C#编译器同时生成Equals的事实和GetHashCode匿名类型:

var filteredBranch = objCustomerData.Select(c =>
 new
 {
     Id = c.Branch,
     BranchName = c.Branch
 }).Distinct().Select(c =>
 new Branch()
 {
     Id = c.Id,
     BranchName = c.BranchName
 }).ToList();

性能方面,第二种方法应该更慢,因为您要创建更多对象,首先是匿名对象,然后是Branch对象。但是如果你正在处理一个相对较小的集合,它就没有多大区别。

相关问题