1

i am picking list of names from database, according to scenario each name exists many times in database, That's ok. Now i have filled a DROPDOWNLIST with those names but in drop down list each name appears several times:

enter image description here

but i want to display each name 1 time in DROPDOWN. I have used distict() but not working.

USING MVC 3, Linq to SQL

Controller:

 namespace EmployeeAttendance_app.Controllers
{
    public class HomeController : Controller
    {
        EmployeeAtdDataContext DataContext = new EmployeeAtdDataContext();

        public ActionResult Index()
        {
            ViewBag.Message = "Precise Technology Consultants";

            //var EmployeeAtd = DataContext.GetAttendance_Sp();
            IEnumerable<GetAtdRecord_SpResult> EmployeeAtd = DataContext.GetAtdRecord_Sp(null).ToList();
            var names = (from n in DataContext.EmployeeAtds select n).Distinct();
            //ViewData["EmplID"] = new SelectList(names, "EmplID", "EmplName");
            return View(EmployeeAtd);

        }
        public ActionResult ddl() 
        {
            var names = (from n in DataContext.EmployeeAtds select n).Distinct();
            ViewData["EmplID"] = new SelectList(names, "EmplID", "EmplName");
            return View();
        }
        public ActionResult showDDL(string EmplID) 
        {
            ViewBag.EmplID = EmplID;
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

Views:

@{
    ViewBag.Title = "ddl";
}

<h2>ddl</h2>

    @using (Html.BeginForm("showDDL", "Home", FormMethod.Get))
    {
        <fieldset>

                Employers 

                 @Html.DropDownList("EmplID", "Select Name")

            <p>

                <input type="submit" value="Submit" />

            </p>

        </fieldset>


    }

ModeL

amespace EmployeeAttendance_app.Models
{
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Data;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Linq;
    using System.Linq.Expressions;
    using System.ComponentModel;
    using System;


    [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="a1")]
    public partial class EmployeeAtdDataContext : System.Data.Linq.DataContext
    {

        private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();

    #region Extensibility Method Definitions
    partial void OnCreated();
    #endregion

        public EmployeeAtdDataContext() : 
                base(global::System.Configuration.ConfigurationManager.ConnectionStrings["a1ConnectionString"].ConnectionString, mappingSource)
        {
            OnCreated();
        }

        public EmployeeAtdDataContext(string connection) : 
                base(connection, mappingSource)
        {
            OnCreated();
        }

        public EmployeeAtdDataContext(System.Data.IDbConnection connection) : 
                base(connection, mappingSource)
        {
            OnCreated();
        }

        public EmployeeAtdDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
                base(connection, mappingSource)
        {
            OnCreated();
        }

        public EmployeeAtdDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
                base(connection, mappingSource)
        {
            OnCreated();
        }

        public System.Data.Linq.Table<EmployeeAtd> EmployeeAtds
        {
            get
            {
                return this.GetTable<EmployeeAtd>();
            }
        }

        [global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetAtdRecord_Sp")]
        public ISingleResult<GetAtdRecord_SpResult> GetAtdRecord_Sp([global::System.Data.Linq.Mapping.ParameterAttribute(Name="EmplID", DbType="Int")] System.Nullable<int> emplID)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), emplID);
            return ((ISingleResult<GetAtdRecord_SpResult>)(result.ReturnValue));
        }
    }

    [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.V_EmployeeAtd")]
    public partial class EmployeeAtd
    {

        private string _EmplID;

        private string _EmplName;

        private string _RecDate;

        private string _RecTime;

        private string _DeptName;

        public EmployeeAtd()
        {
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplID", DbType="Char(8) NOT NULL", CanBeNull=false)]
        public string EmplID
        {
            get
            {
                return this._EmplID;
            }
            set
            {
                if ((this._EmplID != value))
                {
                    this._EmplID = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
        public string EmplName
        {
            get
            {
                return this._EmplName;
            }
            set
            {
                if ((this._EmplName != value))
                {
                    this._EmplName = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecDate", DbType="Char(10)")]
        public string RecDate
        {
            get
            {
                return this._RecDate;
            }
            set
            {
                if ((this._RecDate != value))
                {
                    this._RecDate = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecTime", DbType="Char(5)")]
        public string RecTime
        {
            get
            {
                return this._RecTime;
            }
            set
            {
                if ((this._RecTime != value))
                {
                    this._RecTime = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DeptName", DbType="NVarChar(50)")]
        public string DeptName
        {
            get
            {
                return this._DeptName;
            }
            set
            {
                if ((this._DeptName != value))
                {
                    this._DeptName = value;
                }
            }
        }
    }

    public partial class GetAtdRecord_SpResult
    {

        private string _EmplID;

        private string _EmplName;

        private string _InTime;

        private string _OutTime;

        private string _DateVisited;

        private string _TimeWorked;

        private string _OverTime;

        public GetAtdRecord_SpResult()
        {
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplID", DbType="Char(8) NOT NULL", CanBeNull=false)]
        public string EmplID
        {
            get
            {
                return this._EmplID;
            }
            set
            {
                if ((this._EmplID != value))
                {
                    this._EmplID = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
        public string EmplName
        {
            get
            {
                return this._EmplName;
            }
            set
            {
                if ((this._EmplName != value))
                {
                    this._EmplName = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_InTime", DbType="Char(5)")]
        public string InTime
        {
            get
            {
                return this._InTime;
            }
            set
            {
                if ((this._InTime != value))
                {
                    this._InTime = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_OutTime", DbType="Char(5)")]
        public string OutTime
        {
            get
            {
                return this._OutTime;
            }
            set
            {
                if ((this._OutTime != value))
                {
                    this._OutTime = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateVisited", DbType="Char(10) NOT NULL", CanBeNull=false)]
        public string DateVisited
        {
            get
            {
                return this._DateVisited;
            }
            set
            {
                if ((this._DateVisited != value))
                {
                    this._DateVisited = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_TimeWorked", DbType="Char(5)")]
        public string TimeWorked
        {
            get
            {
                return this._TimeWorked;
            }
            set
            {
                if ((this._TimeWorked != value))
                {
                    this._TimeWorked = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_OverTime", DbType="VarChar(6)")]
        public string OverTime
        {
            get
            {
                return this._OverTime;
            }
            set
            {
                if ((this._OverTime != value))
                {
                    this._OverTime = value;
                }
            }
        }
    }
}

pragma warning restore 1591

Evil rising
  • 442
  • 2
  • 7
  • 21

3 Answers3

1

You need to make sure that your underlying object overrides GetHashCode and Equals in order for it to work properly.

Please see here for more information:

http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

As an example, if you have an object called EmployeeAtd it needs to implement the above two methods in order to know when comparative objects are equal.

This is a simple example but you may consider an EmployeeAtd objects the same if they have matching EmplID's, an example Equals override could be:

public override bool Equals(object obj)
{
    if (obj == null) return false;

    if (this.GetType() != obj.GetType()) return false;

    EmployeeAtd emp = (EmployeeAtd) obj;     

    if (!Object.Equals(EmplID, emp.EmplID)) return false;

    return true;
}

If your EmplID is an int you could simply implement the GetHashCode as follows:

public override int GetHashCode ()
{
    return EmplID.GetHashCode();
}

This is no way best practice but there are plenty of other questions on how to do this.

What is the best way to implement this composite GetHashCode()

Why is it important to override GetHashCode when Equals method is overridden?

Community
  • 1
  • 1
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • sorry, i didn't get you, please if you could say it in easy words, – Evil rising Jan 24 '14 at 12:14
  • Sure, give me few mins. : – hutchonoid Jan 24 '14 at 12:17
  • thanks sir, i have spent nearly a day on fixing it, but couldn't if you can get it fix please, i have other tasks to do ahead so would save my time – Evil rising Jan 24 '14 at 12:18
  • Thanks sir but it's too complicated for a newbie like me, and there must some simple way to reduce duplicates, if you u can sir – Evil rising Jan 24 '14 at 12:31
  • Unfortunately there is not if you are using the Distinct, honestly don't be put off by it. It is a really important concept and one that can be explained easily, and implementing it can be almost copy and paste each time. I will update with a simple analogy but I'm not very good at explaining these things. 2 mins. – hutchonoid Jan 24 '14 at 12:36
  • ok sir, imy id name is EmplID which i also a datavalue of dropdownlist items please sir, put it for me in code – Evil rising Jan 24 '14 at 12:38
  • Ok, try copying and pasting the two above methods into your object then run it again. :) – hutchonoid Jan 24 '14 at 12:40
  • sir it is trowing errors: Error:The name 'EmplID' does not exist in the current context – Evil rising Jan 24 '14 at 12:43
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46002/discussion-between-hutchonoid-and-evil-rising) – hutchonoid Jan 24 '14 at 12:44
1

You can use DISTINCT safely, I am not sure where exactly you are facing problem. Please follow this example. Say I Have a database table this way - enter image description here

Then I write following Stored Procedure

USE [Sample]
GO

CREATE PROCEDURE GiveNames
AS
SELECT DISTINCT(Name) FROM [dbo].[SampleTable]
GO

Then I create a MVC Project and add EDMX and used the content in Controller in following way -

public class EdmxController : Controller
{
    //
    // GET: /Edmx/
    public ActionResult Index()
    {
        DDLModel model = new DDLModel();
        model.Items = new List<string>();

        using (var entities = new SampleEntities1())
        {
            model.Items = entities.GiveNames().ToList();

        }
        return View(model);
    }
}

public class DDLModel
{
    public List<String> Items { get; set; }
}

My View -

@model MVC.Controllers.DDLModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>
    @Html.DropDownList("MyDDL",new SelectList(Model.Items), "--Choose any Item--") 
</div>

And my output doesn't conduct any duplicates -

enter image description here

ramiramilu
  • 17,044
  • 6
  • 49
  • 66
1

I think you are implementing distinct on n which contains all properties of class. You need to apply distinct on required columns only. Like

 var empList= DataContext.EmployeeAtds.Select(n => new
        {
            EmplID= n.EmplID,
            EmplName= n.EmplName
        }).Distinct().ToList();

OR

 var empList= (from n in DataContext.EmployeeAtds select new{ EmplID= n.EmplID,
            EmplName= n.EmplName}).Distinct();
nitish
  • 81
  • 1
  • 7
  • wow 2nd query worked but why and how ? i don't understand the difference – Evil rising Jan 25 '14 at 06:37
  • 1
    Because in above query distinct worked on only two required columns. "Select" eliminated rest of columns those were responsible for repeated entries. – nitish Jan 27 '14 at 09:59