我在.net 2.0 c#
工作我有一组我正在从文件中读取的键/值。所以键可能是相同的,但每个键都有不同的值。
我想按排序顺序列出键,并在网格中显示键,其中列中的关联值与不同的值一样多。我能做什么 ?我尝试使用SortedList类,但它不允许重复键。
in .net 3.0 linq有效,但我需要在.net 2.0中进行。
我该怎么做?
答案 0 :(得分:2)
让我们解决你在两部分中指出的问题:
[a]具有相同键但具有不同值的问题[Soln]在下面的代码片段中设计用户定义的类,即DataKeys。
[b]对列表中的键进行排序[Soln]为用户定义的类实现IComperable。
以下是您可以实施的示例类:
internal class DataKeys : IComparable<DataKeys>
{
private int key;
private string values;
public DataKeys(int key, string values)
{
this.key = key;
this.values = values;
}
internal int Key
{
get { return key; }
}
internal string Values
{
get { return Values; }
}
public int CompareTo(DataKeys other)
{
if (this.key > other.key) return 1;
else if (this.key < other.key) return -1;
else return 0;
}
}
只是根据示例客户端代码检查此代码的执行方式:
private static void Main(string[] args)
{
List<DataKeys> dataRepository = new List<DataKeys>()
{
new DataKeys(10, "Key-10"),
new DataKeys(11, "Key-11"),
new DataKeys(9, "Key-9"),
new DataKeys(8, "Key-8"),
new DataKeys(100, "Key-100")
};
dataRepository.Sort();
foreach (var dataKeyse in dataRepository)
{
Console.WriteLine(dataKeyse.Key);
}
}
输出:
答案 1 :(得分:0)
您可以在您的方案中使用DataTable
:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines("TextFile.txt");
DataTable dt = new DataTable();
dt.Columns.Add("key");
dt.Columns.Add("value");
foreach (string line in lines)
{
string key = line.Split(',')[0];
string value = line.Split(',')[1];
dt.Rows.Add(key, value);
}
dt.DefaultView.Sort="key";
dataGridView1.DataSource = dt;
}
}
TextFile.txt
文本文件:
1,test1
2,test2
3,test3
2,test4
1,test5
1,test6