2012-05-30 47 views
0

我正在使用.NET Framework 3.5創建一個C#2010應用程序。使用C#的Linq庫進行排序

我有一個包含幾個列和行[顯然]一個DataGridView。我將這個datagridview的行保存在表格List<string[]>的結構中。我也有一個List<double>其中包含係數。我想使用System.LINQ庫按係數排序結構。我曾嘗試以下:

var linq_Query_rowrates = 
    from rw in rows 
    orderby matchrate descending 
    select rw; 

這突出的行查詢,並顯示以下錯誤:

Error 1 Could not find an implementation of the query pattern for source type ' System.Collections.Generic.List<string[]> '. ' OrderByDescending ' not found. Are you missing a reference to ' System.Core.dll ' or a using directive for ' System.Linq '?

是否有可能使用LINQ庫,如果是進行排序這種結構, 怎麼樣?

注:我知道很多其他的方法來做到這一點的,我在使用LINQ庫這樣做只是感興趣。

注:matchrate不是各行的成員,但使用行的成員也不起作用。

後來編輯:也許它應該是這樣的?

 var linq_Query_rowrates = 
      from rw in rows 
      join rate in matchrate 
      on matchrate equals rows 
      orderby matchrate descending 
      select rw; 
+4

你有沒有引用「系統。Core.dll',並在源文件中包含'using System.Linq;'指令? – dtb

+0

@dtb,是的,我一直在使用System.Linq的包括;並引用了dll。 –

+0

行和係數如何相關?按索引? – clearpath

回答

2

這是醜陋的,但它的Linq:

  List<string[]> rows = null; 
      List<double> coefficients = null; 

      rows 
       .Select((row, index) => new { Row = row, Index = index }) 
       .Join(coefficients 
          .Select(
           (coefficient, index) => new { Coefficient = coefficient, Index = index }), 
           x => x.Index, 
           x => x.Index, 
           (rowIndex, coefIndex) => new { Row = rowIndex.Row, Coefficient = coefIndex.Coefficient }) 
       .OrderBy(x => x.Coefficient) 
       .Select(x => x.Row); 

我沒有,雖然進行了測試。應該可以將其轉換爲查詢表單。

+0

醜陋,它可能像魅力一樣工作。謝謝。 –

+0

我需要它來實際降序排序。我會如何去做這件事? –

+0

替換'和'OrderByDescending' OrderBy'。 – jrummell

3

假設matchraterw一員,你需要使用下面的語法:

var linq_Query_rowrates = 
    from rw in rows 
    orderby rw.matchrate descending 
    select rw; 

更新

理想情況下,你將有一個導航屬性的速度的關係,所以您的查詢應該是這樣的:

var linq_Query_rowrates = 
    from rw in rows 
    orderby rw.rate.matchrate descending 
    select rw; 

另一種選擇是執行連接。但加入LINQ是醜陋的,我儘量避免它們。

+0

它不是一個成員,但使用行的成員也不起作用。 –

+0

不能通過的東西是不是RW的類型的成員訂購。 – jrummell

+0

好吧,有沒有什麼辦法通過匹配使用LINQ排序行? –

2

如果您係數的集合是指與您的字符串的集合[],你爲什麼要建立2個獨立的,不相關的名單鏈接?當然,只要建立一個非常簡單的結構來保存所有信息以確保每行總是有適當的係數就會更加健壯。它也使排序非常簡單。

public struct CoefficientRow 
{ 
    public double Coefficient; 
    public string[] Cells; 

    public CoefficientRow(double c, string[] cells) 
    { 
     this.Coefficient = c; 
     this.Cells = cells; 
    } 
} 

排序變得輕而易舉......

List<CoefficientRow> rows = new List<CoefficientRow>(); 
//populate the list... 
var orderedRows = rows.OrderBy(cr => cr.Coefficient); 
//or 
var orderedRows = rows.OrderByDescending(cr => cr.Coefficient); 

將它們插入到DataGridView也還是相當簡單:

foreach(var row in rows) 
    this.dgvDataView.Rows.Add(row.Cells); 
1

如果你可以用.NET4,user676571的答案被簡化爲:

IEnumerable<string> query = rows 
    .Zip(coefficients, (r, c) => new {row = r, coef = c}) 
    .OrderByDescending(x => x.coef) 
    .Select(x => x.row); 
+0

不知道這個 - 好。 – clearpath