0

I have a global variable list called objCustomerData I want to be able to return distinct data in GetBranch method.

This is not happening. It is returning all the duplicates. I want it to return just distinct branches.

Please what am I doing wrong here?

        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;
        }
Baba
  • 2,059
  • 8
  • 48
  • 81

2 Answers2

1

Try this,

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

Or

filterBranch = objCustomerData.GroupBy(x => x.Branch).Select(c => new Branch()
{
    Id = c.Key,
    BranchName = c.Key
})).ToList();
  • @user2320476, It is not possible, even GroupBy also returning duplicates? May be the data have spaces or some other characters. –  Jul 04 '15 at 06:15
0

You have to either implement IEquatable<T> on the Branch class or, assuming that Branch.Branch is a string, you can utilize the fact that the C# compiler generates both Equals and GetHashCode for the anonymous types:

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

Performance wise the second approach should be slower, because you are creating more objects, first the anonymous objects, then the Branch objects. But it won't make much difference, if you are dealing with a relatively small collection.

Dzienny
  • 3,295
  • 1
  • 20
  • 30