使用包含不同值的键对键值对进行排序

问题描述:

我正在使用.net 2.0 c#使用包含不同值的键对键值对进行排序

我有一组键/值正在从文件中读取。所以键可以是相同的,但具有与它们中的每一个相关联的不同值。

我想按照排序的顺序列出关键字,并将其显示在网格中,列中的关联值和不同的值一样多。我能做什么 ?我尝试过使用SortedList类,但它不允许重复键。

in .net 3.0 linq工程,但我需要在.net 2.0中。

我该怎么办?

+0

实现'IComparer'。 [看这里的教程](http://www.codeproject.com/Articles/42839/Sorting-Lists-using-IComparable-and-IComparer-Inte)。 – Candide 2013-02-15 11:03:32

+0

作为旁注:您可以在使用大多数C#3.0功能的同时定位.net 2.0 – CodesInChaos 2013-02-16 16:48:07

让我们的地址,你在2个部分中指出的问题:
[一]问题具有相同的键但具有不同的值[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); 
     } 
    } 

输出:

enter image description here

你可以在你的场景中使用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 
+0

我正在使用.net 2.0,是否有var可用 – sudhanshu 2013-02-15 11:39:17

+0

Visual Studio的版本是什么? – 2013-02-15 11:42:49

+0

我已经更新了答案,用显式类型替换'var'的用法。 – 2013-02-15 11:47:57