c#中集合中去除重复项

    技术2025-09-07  68

     问题:取数据库表中DateTime类型字段时,截取年份子串,去除重复字段,如何处理?

     方法:使用Linq中的Lambda表达式,可以轻松实现,以下是简单的示例代码:

     

        public void BindNF()    {        //这里要去除相同的年份,通过Linq的Lambda表达式实现        DM dm = new DM();        string strSQL = "select * from [预警记录] ";        DataSet ds = dm.getsql(strSQL);        ArrayList al = new ArrayList();        foreach (DataRowView drv in ds.Tables[0].DefaultView)        {            al.Add(drv["发布时间"].ToString().Substring(0, drv["发布时间"].ToString().IndexOf("-")));        }        //构造泛型集合        List<string> years = new List<string>();        for (int i = 0; i < al.Count; i++)        {            years.Add(al[i].ToString());        }

            //Distinct()方法用于返回序列中的非重复元素        var result = years.Distinct();

            this.ddlNF.DataSource = result;        this.ddlNF.DataBind();    }

     

    2、另外一种非LINQ实现方法,利用普通的循环比较方法也可以实现:

            string s1= "a,b"; string s2 = "a,b,c,d"; string[] str1 = s1.Split(','); string[] str2 = s2.Split(','); string s3 = ""; bool flag = true; foreach (string tempS in str2) { flag = true; foreach (string tempS2 in str1) { if (tempS2 == tempS) { flag = false; break; } } if (flag) { s3 += tempS + ","; } } if (s3 != "") { s3 = s3.Remove(s3.Length - 1, 1); } Response.Write(s3);

    最新回复(0)