基于另一个列表中的另一个属性对列表进行排序

时间:2014-02-20 08:33:08

标签: c#

我有以下对象:

public class CustomerSequence
{
    public string CustomerName  { get; set; } 
    public int Sequence { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Component { get; set; } 
}

假设我有2个列表对象

Customer:                             CustomerSequence:
Id         Name        Component      CustomerName         Sequence
1          AAA         AAAAAA         AAA                  2
2          BBB         BBBBBBB        BBB                  4
3          CCC         CCCCC          CCC                  1
                                      DDD                  3

如您所见,列表中没有 DDD

我想根据列表 CustomerSequence

对List 客户进行排序

结果是:

Customer:
Id         Name        Component
3          CCC         CCCCC
1          AAA         AAAAAA
2          BBB         BBBBBBB        

任何人都可以帮助我。

4 个答案:

答案 0 :(得分:3)

将两个序列加入客户名称,然后按顺序值排序:

from c in customers
join cs in customerSequences
    on c.Name equals cs.CustomerName
orderby cs.Sequence
select c;

Lambda语法不是很漂亮,看起来像

customers.Join(customerSequences, 
               c => c.Name, cs => cs.CustomerName, (c,cs) => new { c, cs })
         .OrderBy(x => x.cs.Sequence)
         .Select(x => x.c)

内部连接使用查找第二个序列,这比Where的线性搜索更有效。


如果可能没有CustomerSequencs匹配客户,或者有多个匹配,则使用组加入:

from c in customers
join cs in customerSequences
    on c.Name equals cs.CustomerName into g
orderby g.Select(cs => cs.Sequence).FirstOrDefault() 
select c

此查询使用0表单缺失序列,如果客户有多个序列,则使用第一个匹配值。

答案 1 :(得分:2)

试试这个

Customer.OrderBy(x => CustomerSequence.Where(y => y.CustomerName == x.Name)
                                      .Select(y => y.Sequence)
                                      .FirstOrDefault())

或者,如果源是数据库,则可以使用更好的连接

var sorted = 
from c in customer
join csj in customerSequence on c.Name equals csj.CustomerName into customerSequenceJoined
from cs in customerSequenceJoined.DefaultIfEmpty()
orderby cs == null ? 0 : cs.Sequence
select c;

cs == null ? 0 : cs.Sequence处理序列集合中没有匹配记录的情况。如果您希望这些项目最后显示,则可以使用int.MaxValue

答案 2 :(得分:1)

使用加入

var customers = from cust in Customer
                     join cust_seq in CustomerSequence
                     on cust.Name equals cust_seq.CustomerName         
                     orderby cust_seq.Sequence
                     select cust;

答案 3 :(得分:0)

我倾向于使用字典来处理这类事情。

var customerSequence =
    customerSequences
        .ToDictionary(x => x.CustomerName, x => x.Sequence);

var sortedCustomers = 
    customers
        .OrderBy(x => customerSequence[x.Name])
        .ToList();