LINQ To SQL IN 與排序

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

摘要:LINQ To SQL IN 與排序

 

    承上篇,讀者繼續詢問排序問題,如要依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);
            }

            Console.ReadLine();
        }


        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)
                    result.Add(ditem);
            }

            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
11         Console.ReadLine()
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
20                 result.Add(ditem)
21             Next
22         Next
23         Return result
24     End Function

25
26 End Module

 

請注意,ToList後就已成為離線模式,接下來的CustomSort不會送出任何SQL指令.