2012-05-30 48 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