就是下拉選單的資料是從現有的方法來的
下拉選單的資料不應該有重複
但問題現有的方法沒辦法做distinct過濾重複的資料
又不能自己寫ADO.NET連資料庫
所以你還是只能用他給你的資料做處理
比較土法煉鋼的方式就是寫一個陣列判斷陣列中有無該值
有就繼續下一個沒有就存進陣列
但這種方式的時間複雜度應該也是最差的
其實類似的問題之前在Java已經有解過-大樂透程式
在C#上我找到的方法是使用Enumerable的Distinct方法
最後解法如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class distinct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
List<distinctexample> list = new List<distinctexample>();
list.Add(new distinctExample(45));
list.Add(new distinctExample(32));
list.Add(new distinctExample(9));
list.Add(new distinctExample(32));
list.Add(new distinctExample(66));
foreach (distinctExample x in list)
{
Response.Write(x.number+" ");
}
Response.Write("
");
IEnumerable<distinctexample> distinctList = list.Distinct();
foreach (distinctExample distinctResult in distinctList)
{
Response.Write(distinctResult.number+" ");
}
}
}
public class distinctExample : IEquatable<distinctexample>
{
public bool Equals(distinctExample anyNumber)
{
if(Object.ReferenceEquals(anyNumber,null))
return false;
if (Object.ReferenceEquals(this, anyNumber))
return true;
return number.Equals(anyNumber.number);
}
public override int GetHashCode()
{
int hashdistinctExample = number == null ? 0 : number.GetHashCode();
return hashdistinctExample;
}
public distinctExample(int number)
{
this.number = number;
}
public int number
{
get;
set;
}
}
記得實作Equals跟GetHashCode這兩個方法才能進行distinct
Enumerable也有提供不少常用的方法像是OrderBy、Max、Min、Reverse...
參考資料:Enumerable.Distinct
Enumerable 方法
C# 3.0 泛型集合 Generic Collection 中的 List
沒有留言:
張貼留言