Skip to content

Instantly share code, notes, and snippets.

@afreeland
Created July 9, 2013 16:32
Show Gist options
  • Save afreeland/5958892 to your computer and use it in GitHub Desktop.
Save afreeland/5958892 to your computer and use it in GitHub Desktop.
C#: Lambda Update or Create object in collection
// Extension method to interrogate a collection for a particular property and value
// If it does not exist create a new object
// return object found or created
public static T GetOrAdd<T>(this IList<T> list, Func<T, bool> predicate, Func<T> constructor)
{
var match = list.FirstOrDefault(predicate);
if (match == null)
{
match = constructor();
list.Add(match);
}
return match;
}
// GetOrAdd Extension method implemented with Order_Attributes
public ActionResult EditVoucherEntries(string row)
{
var rowObject = nChannel.Framework.v1_0.Utilities.JsonToXml.ConvertJsonToNameValuePair(row);
Order_Order o = GetObject<Order_Order>(API.Get(API.Orders.Actions.orderbyid, AccountID.ToString(), rowObject["id"]));
o.Order_Attributes.GetOrAdd(x => x.Name == "Adjustment", () => new Order_Attribute() { Name = "Adjustment" }).Value = rowObject["adj"];
o.Order_Attributes.GetOrAdd(x => x.Name == "InvoiceDate", () => new Order_Attribute() { Name = "InvoiceDate" }).Value = rowObject["invd"];
o.Order_Attributes.GetOrAdd(x => x.Name == "InvoiceDueDate", () => new Order_Attribute() { Name = "InvoiceDueDate" }).Value = rowObject["invdd"];
o.Order_Attributes.GetOrAdd(x => x.Name == "InvoiceNumber", () => new Order_Attribute() { Name = "InvoiceNumber" }).Value = rowObject["invn"];
Order_Orders orders = new Order_Orders();
orders.Add(o);
SendObject<Order_Orders>(API.Get(API.Orders.Actions.ordersupdate, AccountID.ToString()), APIAction.Update, orders);
return Json(o);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment