2014-02-11 143 views
-4

讓我再次問這個問題排序字符串列表

說我有一個數據庫,一個是任務的兩個表,另一個是依賴

任務表中有一列(TASKNAME)所有的任務需要運行

的taskDependency表有2列一個是任務(taskNames)和其他依賴(taskDependsOn)

現在說我選擇的任務表中的任務成一個列表,爲的依賴依賴新生(字典不會工作,因爲一些任務有多個依賴關係)

如何將任務按順序排列?

編輯

我在另一個論壇上得到了答案,並認爲在這裏分享它。

你可以使用一個字典,你只需要明智地使用它!

嘗試使用字典>其中密鑰是任務名稱,值是密鑰所依賴的任務的任務名稱集合。

爲每個可能的任務預先加載一個空的HashSet字典(表1)。 從數據庫中更新它(表2) 創建空輸出列表 然後命令爲: 1.找到具有空依賴集的鍵,此組中沒有順序,將它們追加到輸出列表(並刪除他們從字典)。 保留這些的單獨列表。 1a。如果字典是空的,你就完成了。 1b。如果沒有找到空的依賴關係集,那麼你有依賴關係週期!失敗。 2.所有字典中的剩餘組(即,dictionary.Values)從所述一組 3.刪除所有在步驟1 4.回發現的任務到步驟1。

感謝名單墊從CodeProject

+1

用什麼語言?根據列表2進行排序? – herohuyongtao

+3

不清楚你想要什麼。舉個例子。排序後,你希望列表1看起來像什麼樣子。 –

+0

您是否在兩個容器中都有固定數量的元素? – user1767754

回答

1

目前尚不清楚你的數據結構是什麼(列表或數組),但如果list1list<string>string[]list2List<List<string>>List<string[]>string[][]那麼查詢將是:

from str in list1 
join pair in list2 on str = pair[0] 
order by pair[1] 
select str 
1
static void Main(string[] args) 
    { 
     Dictionary<string, string> ordering = new Dictionary<string, string>() 
      { 
       { "g", "d" }, { "s", "e" }, { "e", "g" } 
      }; 
     List<string> source = new List<string>() { "e", "s", "g" }; 

     List<string> result = source.OrderBy(key => ordering[key]).ToList(); 

     foreach (string s in result) { Console.Write(s + " "); } 
     Console.WriteLine(); 
    } 

結果是g s e

+0

如果一件物品取決於多個值/ – Ernie

+0

然後更改OrderBy!的值! – plinth

+0

但字典cnt有2個相同的鍵 – Ernie

0

矢量排序,我們按照另一個順序排列一個矢量?像這樣?

// first, our base data 
Tuple<char,char>[] data = { new Tuple<char,char>('g','d') , 
          new Tuple<char,char>('s','e') , 
          new Tuple<char,char>('d','s') , 
          new Tuple<char,char>('e','g') , 
          } ; 

// initialize the two vectors 
List<char>    keys = new List<char>(data.Select(x => x.Item1)) ; // {g,d,s,e} 
List<Tuple<char,char>> values = new List<Tuple<char, char>>(data) ; 

// An in-place sort of the "keys" vector in terms of the payload of the "values" vector 
keys.Sort((x,y) => { 

    // first, find the associated value for each key (if such exists) 
    char? xValue = null ; 
    char? yValue = null ; 
    foreach (Tuple<char, char> t in values) 
    { 
    if (t.Item1 == x && !xValue.HasValue) xValue = t.Item2 ; 
    if (t.Item1 == y && !yValue.HasValue) yValue = t.Item2 ; 
    // if we found both values, we can quit     
    if (xValue.HasValue && yValue.HasValue ) break ; 
    } 

    // set the condition (comparison code) 
    int cc ; 
    if  (xValue.HasValue && yValue.HasValue) cc = xValue.Value.CompareTo(yValue.Value) ; 
    else if (xValue.HasValue     ) cc = +1 ; // treat NULL as collating lower than non-null 
    else if (     yValue.HasValue) cc = -1 ; // treat NULL as collating lower than non-null 
    else           cc = 0 ; // equal if both are NULL 

    // return it 
    return cc ; 
});