### LINQ To SQL IN 與排序

• 13881
• 0
• LINQ
• 2009-02-05

承上篇,讀者繼續詢問排序問題,如要依IN時傳入元素的順序排列,該如何做?

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext context = new DataClasses1DataContext();
context.Log = Console.Out;
var result = from s1 in context.Customers where (new string[] { "UK", "Lisboa" }).Contains(s1.City) select s1;
var result2 = CustomSort(result.ToList(), new string[] { "UK", "Lisboa" });
foreach (var item in result2)
{
Console.WriteLine(item.City);
}

}

static List<Customers> CustomSort(List<Customers> list,string[] citys)
{
List<Customers> result = new List<Customers>();
foreach (var item in citys)
{
var query = from s1 in list where s1.City == item select s1;
foreach (var ditem in query)
}

return result;
}

}

}

VB.NET

01 Module Module1
02
03     Sub Main()
04
05         Dim context As New DataClasses1DataContext()
06
07         Dim lists = From s1 In context.Customers Where (New String() {"UK", "Lisboa"}).Contains(s1.City) Select s1
08         For Each item In CustomSort(lists.ToList(), New String() {"UK", "Lisboa"})
09             Console.WriteLine(item.City)
10         Next
12     End Sub

13
14     Function CustomSort(ByVal source As List(Of Customers), ByVal citys As String())
15         Dim result As New List(Of Customers)
16         For Each item In citys
17             Dim localItem = item
18             Dim query = From s1 In source Where s1.City = localItem Select s1
19             For Each ditem In query