LinQ to Object --- 有关于Dictionary、SQL(LEFT OUTER JOIN \ Group OrderBy Sum) 操作
Dictionary操作
c#
var vhe = new Dictionary<String,String>();
var queryString = context.Request.QueryString;
foreach ( string item in queryString ) {
vhe.Add ( item , CommonFunc.ConvertObjectToString ( queryString[item] ) );
}
return vhe;对以上C#代码用LinQ To Object 进行Coding
LinqToObject
1:
var query = from item in queryString.OfType<String> () select new KeyValuePair<string , string> ( item , queryString[item] ); var vhe = new Dictionary<String , String> (); foreach ( var item in query ) { vhe.Add ( item.Key.ToString () , item.Value.ToString () ); }return vhe;
2:
return queryString.OfType<String> () .ToDictionary ( item => item , item => queryString[item] );
LEFT OUTER JOIN 操作
SQL:
代码
SELECT [t0].[MemberID], [t0].[MemberName]
FROM [dbo].[MemberInfo] AS [t0]
LEFT OUTER JOIN [dbo].[MemberSort] AS [t1] ON ( [t1].[MemberType] = 0 ) AND
( [t0].[MemberID] = [t1].[MemberID] )
ORDER BY ( CASE WHEN [t1].[SortNumber] IS NOT NULL THEN [t1].[SortNumber]
ELSE 9999
END )
LINQ:
代码
var data = from m in db.MemberInfo
join s in db.MemberSort on m.MemberID equals s.MemberID
into x
from cx in x.Where(d => d.MemberType == 0).DefaultIfEmpty()
orderby cx.SortNumber.HasValue ? cx.SortNumber.Value : 9999
select m;
Group OrderBy Sum操作
SQL:
代码
SELECT [SID], CID, SUM(VisitCount), SUM(ResultCount), SUM(ValidCount)
FROM dbo.CountVisit
WHERE ReportDate BETWEEN '2010-03-04' AND '2010-03-08' AND
[SID] LIKE '%m%'
GROUP BY [sid], CID
ORDER BY [SID], CID
LINQ:
代码
var list = new List<CountVisitEntity> ();
using ( var tb = GetCountVisitByParam ( svcp , ref flipPageOption ) ) {
if ( tb.Rows.Count > 0 ) {
var query = from item in tb.AsEnumerable ()
group item by new { SID = item.Field<String> ( "SID" ) ,
CID = item.Field<String> ( "CID" )
} into result
orderby result.Key.SID , result.Key.CID
select new CountVisitEntity () {
SID = result.Key.SID ,
CID = result.Key.CID ,
XX = result.Sum ( o => o.Field<Int32> ( "XX" ) ) ,
XXX = result.Sum ( o => o.Field<Int32> ( "XXX" ) ) ,
XXXX = result.Sum ( o => o.Field<Int32> ( "XXXX" ) )
};
list = query.ToList ();
}
}
return list;