2013-02-15 53 views
1

我正在使用.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

讓我們的地址,你在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

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 
+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

相關問題