2014-02-20 60 views
1

我有如下的對象:排序基於另一個列表中的其他屬性的列表

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

結果是對列表進行排序客戶

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

任何人都可以幫我請。

+0

如果序列表中沒有匹配的行,那麼期望的行爲是什麼? –

+0

@BobVale我不會讓它發生,因爲我選擇基於CustomerSequence.CustomerName的列表。 –

回答

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形式缺少的序列,和第一匹配如果客戶有多個序列,則爲價值。

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

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; 
+0

嗨,我相信是order by cust_seq.Sequence。 –

+0

沒錯,你是對的,忽略了那個,並假設你會得到它;) –

0

我傾向於使用字典這樣的事情。

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

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