簡體   English   中英

使用C#的Linq庫排序

[英]Sorting using C#'s Linq library

我正在使用.NET Framework 3.5創建C#2010應用程序。

我有一個datagridview,其中包含一些列和行[很明顯]。 我將此Datagridview的行保存為List<string[]>形式的結構。 我也有一個包含系數的List<double> 我想使用System.LINQ庫按系數對結構進行排序。 我嘗試了以下操作:

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

這使查詢中的行成為下划線並顯示以下錯誤:

錯誤1找不到源類型' System.Collections.Generic.List<string[]> '的查詢模式的實現。 找不到“ OrderByDescending ”。 您是否缺少對“ System.Core.dll ”的引用或對“ System.Linq ”的using指令?

可以使用LINQ庫對這種結構進行排序嗎?如果可以,怎么辦?

注意:我知道有很多其他方法可以完成此操作,我只是想使用LINQ庫來完成它。

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

稍后編輯:也許應該是這樣的?

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

假設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中的聯接很難看,我盡量避免。

很難看,但是是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);

我還沒有測試過。 應該可以將其轉換為查詢形式。

如果您的系數集合是要與string []集合鏈接的,那么為什么要構建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);

如果可以使用.Net4,則user676571的答案可簡化為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM