You must Sign In to post a response.
  • Category: .NET

    How to return Distinct values from List in c#.net

    I have below methods , I am not able to return list , please correct me below methods , how write correct method
    public List<string> GetOwners()
    {
    //string[] owners = { "dqvu@chevron.com", "prja@chevron.com", "prja@chevron.com" };
    // return owners.Distinct().ToArray();
    List<string> b = new List<string>();
    List<string> DistinctNames;
    using (OracleConnection con = new OracleConnection(connectionString()))
    {
    con.Open();
    string OrclStr = "SELECT OWNER_ID || '@chevron.com' as owners FROM DOCSADM.SAS_GROUP_OWNER";
    OracleCommand cmd = new OracleCommand(OrclStr, con);
    cmd.CommandType = CommandType.Text;
    OracleDataReader r = cmd.ExecuteReader();
    while (r.Read())
    {
    b.Add(Convert.ToString(r["owners"]));
    DistinctNames = b.Distinct().ToList();
    }
    }

    return DistinctNames;

    }
  • #769113
    Hi,

    Kindly let us know what is the issue you are getting when you run the above code.

    Thanks,
    Mani

  • #769124
    Hi,

    Try this

    List<Class> objlst = new List<Class>();
    objlst.Select(x => x.ClassName).Distinct();


    Hope this helps you..

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #769170
    Here is the example to return Distinct values from List in c#.net Using the IEqualityCompare<T> interface
    class ProductComparer : IEqualityComparer<Product>  
    {
    public bool Equals(Product x, Product y) {
    if (Object.ReferenceEquals(x, y)) return true;

    if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
    return false;

    return x.Make == y.Make && x.Model == y.Model;
    }
    public int GetHashCode(Product product) {
    if (Object.ReferenceEquals(product, null)) return 0;
    int hashProductName = product.Make == null ? 0 : product.Make.GetHashCode();
    int hashProductCode = product.Model.GetHashCode();
    return hashProductName ^ hashProductCode;
    }
    }


    if (!IsPostBack) {
    GridView1.DataSource = GetProducts()
    .Distinct(new ProductComparer());
    GridView1.DataBind();
    }


Sign In to post your comments