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

Module Module1

Sub Main()

Dim context As New DataClasses1DataContext()

Dim lists = From s1 In context.Customers Where (New String() {"UK", "Lisboa"}).Contains(s1.City) Select s1
For Each item In CustomSort(lists.ToList(), New String() {"UK", "Lisboa"})
Console.WriteLine(item.City)
Next
Console.ReadLine()
End Sub

Function CustomSort(ByVal source As List(Of Customers), ByVal citys As String())
Dim result As New List(Of Customers)
For Each item In citys
Dim localItem = item
Dim query = From s1 In source Where s1.City = localItem Select s1
For Each ditem In query
result.Add(ditem)
Next
Next
Return result
End Function

End Module

請注意,ToList後即進入離線模式,接下來的CustomSort不會送出任何SQL指令.

阅读更多
文章标签: Linq SQL VB VB.NET .net
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭