2008-05-11

Die let-Klausel (clause) in LINQ

Für die Erstellung einer temporären Variable innerhalb einer Query Expression kann das Schlüsselwort let verwendet werden. Mithilfe einer Formel wird an diese Variable ein neuer Wert aus bestehenden Daten zugewiesen. Die Variable ist dann innerhalb der Query Expression weiterverwendet und bei Bedarf im Select-Block ausgegeben werden.

Die Lesbarkeit des Codes wird durch die Verwendung von Schlüsselwort let gesteigert und der Code bleibt übersichtlich.

In dem folgenden Beispiel werden mithilfe des let-Schlüsselwortes zwei Variablen (DistributorPrice und ProductColorIsBlack) erstellt.

Die Variable DistributorPrice beinhaltet den Wert des Händlerpreises. Dieser Preis wird mithilfe des Faktors 0.75 vom Listenpreis berechnet.
let DistributorPrice = (p.ListPrice*Convert.ToDecimal(0.75))

Die Variable ProductColorIsBlack beinhaltet den Wert, ob die Produktfarbe Schwarz ist.
let ProductColorIsBlack = (p.Color != null && p.Color == "Black")

Innerhalb des Select-Blocks werden die beiden Variablen ausgegeben.
select new
{
ProductCategoryName = pc.Name,
ProductSubCategoryName = psc.Name,
ProductName = p.Name,
p.ListPrice,
DistributorPrice,
ProductColorIsBlack
};

Der gesamte Beispiel Code ist wie folgt aufgelistet:

using System;
using System.Linq;

namespace LinqLetSample0001
{
internal class Program
{
private static void Main(string[] args)
{
var db
= new AdventureWorksDataContext();

var qry
= from pc in db.ProductCategories
join psc
in db.ProductSubcategories on pc.ProductCategoryID equals psc.ProductCategoryID
join p
in db.Products on psc.ProductSubcategoryID equals p.ProductSubcategoryID
let DistributorPrice
= (p.ListPrice * Convert.ToDecimal(0.75))
let ProductColorIsBlack
= (p.Color != null && p.Color == "Black")
select
new
{
ProductCategoryName
= pc.Name,
ProductSubCategoryName
= psc.Name,
ProductName
= p.Name,
p.ListPrice,
DistributorPrice,
ProductColorIsBlack
};

foreach (var item in qry)
{
Console.WriteLine(
"Product Category : " + item.ProductCategoryName);
Console.WriteLine(
"Product Sub Category : " + item.ProductCategoryName);
Console.WriteLine(
"Product : " + item.ProductName);
Console.WriteLine(
"Product Distributor Price: " + item.DistributorPrice);
Console.WriteLine(
"Product List Price : " + item.ListPrice);
Console.WriteLine(
"Product Color is Black : " + item.ProductColorIsBlack);
Console.WriteLine();
}

Console.ReadLine();
}
}
}


Das komplette Visual Studio 2008 Projekt kann unter folgende URL heruntergeladen werden: LinqLetSample0001.zip







No comments: