开发的股票程序遇到两个问题:
- 股票数据重复。
- listbox控件文件不能对齐。
网上查询了一些资料,对listbox对齐的方法还是没搞明白。
不过今天无意中进行数据去重的时候,listbox对齐了,原理没搞懂。。先记录下来。
可能是在准备数据阶段填充了空格,又重写了tostring()方法,然后listbox会自动对齐??
List<IndusIndex> temp = new List<IndusIndex>();
//分割,准备数据去重
foreach (var item in result)
{
var a = item.Split('\t');
//文本对齐,和IndusIndex中的stringformat配合,缺一不可
var s= string.Join(" ,", a).Split(',');
temp.Add( new IndusIndex(s[0],s[1],s[2]));
}
//利用自定义规则去重
listBoxstock.ItemsSource = temp.Distinct(new Compare());
//listBoxstock.ItemsSource = temp;
}
}
//为了数据去重,定义一个最后挑出的股票列表类
class IndusIndex
{
public string ID { get; set; }
public string NAME { get; set; }
public string INDUS { get; set; }
public IndusIndex(string id, string name, string indus)
{
ID = id;
NAME = name;
INDUS = indus;
}
//必须重写tostring,否则无法识别
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}", this.ID, this.NAME, this.INDUS);
}
}
//引用类型的数据去重,定义规则
class Compare : IEqualityComparer<IndusIndex>
{
public bool Equals(IndusIndex x, IndusIndex y)
{
return x.NAME == y.NAME;//可以自定义去重规则,此处将NAME相同的就作为重复记录,不管其他
}
public int GetHashCode(IndusIndex obj)
{
return obj.NAME.GetHashCode();//哈希码相同视为相同
}
}