Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Friday, June 11, 2010

Using ConvertAll and Aggregate in LINQ


string strImportResult = this.ImportResult.ToList()
.ConvertAll<string>(Import => string.Format("<tr><td>
{0}</td><td>{1}</td><td>{2}</td><td>
{3}</td></tr>"

, Import.CustodianName
, Import.ImportFile
, Import.ImportStatus
, Import.Particular))
.Aggregate((ImportA, ImportB) => ImportA + ImportB);

Multipal Field Group By IN LINQ



var objOrderList = from OrderList in
(from OrderDetail in objOrderDetail
join Item in objItem on OrderDetail.ItemId equals Item.ItemId
join ItemGroup in objItemGroup on Item.GroupId equals ItemGroup.GroupId
select new
{
GroupName = ItemGroup.GroupName,
ItemName = Item.ItemName,
Rate = Item.Rate,
Qty = OrderDetail.Qty
}
)
group OrderList by new
{
OrderList.GroupName,
OrderList.ItemName
} into OrderList
select new
{
GroupName = OrderList.Key.GroupName,
ItemName = OrderList.Key.ItemName,
OrderTotal = OrderList.Sum(OL => OL.Qty * OL.Rate)
};

Left Outer Join and Group By In LINQ


List Table1 = new List();
List Table2 = new List();

var objList = from ListData in
(from a in Table1
join b in Table2 on a.Id equals b.Id into t2
from t2Data in t2.DefaultIfEmpty()
select new
{
Product = a.Product,
Title = t2Data.Title,
Amount = a.Amount
}
)
group ListData by new
{
ListData.Product,
ListData.Title
} into GroupData
select new
{
Product = GroupData.Key.Product,
Title = GroupData.Key.Title,
Amount = GroupData.Sum(OL => OL.Amount)
};

Sunday, January 31, 2010

LINQ Extended method for Update Data

Extended Method

public delegate void Func(TArg0 element);

///
/// Executes an Update statement block on all elements in an IEnumerable sequence.
///
/// The source element type.
/// The source sequence.
/// The update statement to execute for each element.
/// The numer of records affected.
public static int Update(this IEnumerable source, Func update)
{
if (source == null) throw new ArgumentNullException("source");
if (update == null) throw new ArgumentNullException("update");
if (typeof(TSource).IsValueType)
throw new NotSupportedException("value type elements are not supported by update.");

int count = 0;
foreach (TSource element in source)
{
update(element);
count++;
}
return count;
}

Example :

int intUpdate = lstItem
.Where(a => a.ItemGroupId.Equals(lngItemGroupId))
.Update(b =>
{
b.GroupName = strGroupName;
b.GroupLocation = strLocation;
}
);