I want to achieve the below format data from to different List.
Using the below code:
List<SalesOrder> SalesOrder = new List<SalesOrder>();
List<Sales> Sales = new List<Sales>();
SalesOrder.Add(new SalesOrder { VoucherNumber = "1", Date = "01-04-2018", LedgerName = "Sales Party", Refernce = "1", StockItem = "Item 1", Description = "", qnt = "1200", Rate = "120", Amount = "14000" });
SalesOrder.Add(new SalesOrder { VoucherNumber = "1", Date = "01-04-2018", LedgerName = "Sales Party", Refernce = "1", StockItem = "Item 2", Description = "", qnt = "78", Rate = "980", Amount = "76440" });
SalesOrder.Add(new SalesOrder { VoucherNumber = "2", Date = "04-04-2018", LedgerName = "Sales Party", Refernce = "2", StockItem = "Item 3", Description = "", qnt = "350", Rate = "345", Amount = "120750" });
Sales.Add(new Sales { VoucherNumber = "1", Date = "05-04-2018", Refernce = "1", LedgerName = "SalePartyLedgerName", Description = "", qnt = "100 nos", Rate = "120", Amount = "12000" });
Sales.Add(new Sales { VoucherNumber = "1", Date = "05-04-2018", Refernce = "1", LedgerName = "SalePartyLedgerName", Description = "", qnt = "40 nos", Rate = "980", Amount = "39200" });
var res = from so in SalesOrder
join s in Sales
on so.VoucherNumber equals s.Refernce into ps
from s in ps.DefaultIfEmpty()
select new
{
SONO = so.VoucherNumber,
SODate = so.Date,
SoCustomer = so.LedgerName,
SoItem = so.StockItem,
SoDescription = so.Description,
SoUnit = so.qnt,
SoRate = so.Rate,
SoAmount = so.Amount,
SInvNum = s?.VoucherNumber ?? string.Empty,
SDate = s?.Date ?? string.Empty,
SQnt = s?.qnt ?? string.Empty,
SRate = s?.Rate ?? string.Empty,
SAmount = s?.Amount ?? string.Empty
};
I am getting the following result:
I want to merge those two List's based on a ref number. Currently what i have tried is based on left join but the item is getting repeated by number of item present in the 2nd list. You may note that 1st image show only 2 line of data containing "1" as a number and my c# code is creating 4 of them and data is also getting repeated and spitted in next line too.
What changes i need to do for getting the result what i want?
Any help with an example will be greatly appreciated.
Sorry for my bad English.
Related
I have a list of objects that I need to pull values from and save to another list. If there are duplicate name values, I need to choose the entry that is closet to the provided effective date. I'm trying to do this with a number of if statements but it's a mess and isn't functioning as expected. I would imagine that there's a simpler way to do this using LINQ but I don't know how to filter out both conditions.
here is my object class
class ExcelMessageRows
{
public string Name { get; set; }
public string State { get; set; }
public DateTime Date { get; set; }
public string Message { get; set; }
}
//Here is the code using nested if statements -
List<ExcelMessageRows> compareRows = new List<ExcelMessageRows>();
compareRows.Add(new ExcelMessageRows { Name = "1", Date = DateTime.FromOADate(12/1/1997), Message = "a2" });
compareRows.Add(new ExcelMessageRows { Name = "1", Date = DateTime.FromOADate(12/1/2005), Message = "a3" });
compareRows.Add(new ExcelMessageRows { Name = "1", Date = DateTime.FromOADate(12/1/2015), Message = "a4" });
compareRows.Add(new ExcelMessageRows { Name = "2", Date = DateTime.FromOADate(12/1/1997), Message = "a5" });
compareRows.Add(new ExcelMessageRows { Name = "3", Date = DateTime.FromOADate(12/1/1998), Message = "a6" });
compareRows.Add(new ExcelMessageRows { Name = "3", Date = DateTime.FromOADate(12/1/2006), Message = "a7" });
compareRows.Add(new ExcelMessageRows { Name = "4", Date = DateTime.FromOADate(12/1/2015), Message = "a8" });
compareRows.Add(new ExcelMessageRows { Name = "5", Date = DateTime.FromOADate(12/1/1998), Message = "a9" });
compareRows.Add(new ExcelMessageRows { Name = "6", Date = DateTime.FromOADate(12/1/1999), Message = "a10" });
compareRows.Add(new ExcelMessageRows { Name = "7", Date = DateTime.FromOADate(12/1/1997), Message = "a11" });
compareRows.Add(new ExcelMessageRows { Name = "7", Date = DateTime.FromOADate(12/1/2014), Message = "a12" });
compareRows.Add(new ExcelMessageRows { Name = "7", Date = DateTime.FromOADate(12/1/2016), Message = "a13" });
//SETTING AN EFFECTIVE DATE AND STATE
DateTime effectiveDate = DateTime.Now;
//FINAL LIST OF MESSAGES
List<string> decMessages = new List<string>();
int previousRow = 1;
compareRows.OrderBy(x => x.Name);
foreach (ExcelMessageRows mRows in compareRows)
{
if (mRows.Name.Equals(compareRows[previousRow - 1].Name))
{
if (effectiveDate > mRows.Date
&& effectiveDate > compareRows[previousRow - 1].Date)
{
decMessages.Add(mRows.Message);
}
if (effectiveDate < mRows.Date
&& effectiveDate > compareRows[previousRow - 1].Date)
{
decMessages.Add(compareRows[previousRow - 1].Message);
}
}
else
{
decMessages.Add(compareRows[previousRow - 1].Message);
}
previousRow++;
}
foreach (string mes in decMessages)
Console.WriteLine(mes);
}```
this code will add the closest message per name to the list. always use linq with caution. short code doesnt mean short runtime complexity.
var groups = compareRows.GroupBy(p => p.Name);
var decMessages = new List<string>();
foreach (var group in groups)
decMessages.Add(group.OrderBy(p => Math.Abs(effectiveDate.Subtract(p.Date).TotalMilliseconds)).Last().Message);
What you need to do is group by name so you can select the nearest of each group:
var decMessages = compareRows.GroupBy(r => r.Name)
.Select(rg => rg.OrderBy(r => effectiveDate-r.Date).First().Message)
.ToList();
I am currently trying to integrate the PayPal smart button to my asp.net core web application. I've referenced the following API documentation to set up a transaction with the PayPal API from my server: https://developer.paypal.com/docs/checkout/reference/server-integration/set-up-transaction/#on-the-server. However, the documentation hardcoded the line-items in the PayPal order request body. Right now, I have a variable called lineItems that contains a list of products that I want to send to PayPal. How do I dynamically create the lineItems at the BuildRequestBody() method? Below is my current code:
Update I am still trying to solve this issue. Help is greatly appreciated!
Update2 Still trying to solve this issue, help is greatly needed.
Update3 Is anyone having the same issue as me? The documentation is extremely vague and I need help.
Update4 No progress, still in need of help!
public async Task<HttpResponse> createPaypalTransaction()
{
List<Product> lineItems = new List<Product>();
decimal totalPrice = 4.00;
lineItems.Add(new Product
{
ProductId = 1,
ProductName = "T-Shirt",
Quantity = 2,
Price = 2.00M
});
lineItems.Add(new SanitizeProduct
{
ProductId = 2,
ProductName = "Shoe",
Quantity = 2,
Price = 2.00M
});
var request = new OrdersCreateRequest();
request.Prefer("return=representation");
request.RequestBody(BuildRequestBody());
//3. Call PayPal to set up a transaction
var response = await PayPalClient.client().Execute(request);
var result = response.Result<PayPalCheckoutSdk.Orders.Order>();
Console.WriteLine("Status: {0}", result.Status);
Console.WriteLine("Order Id: {0}", result.Id);
Console.WriteLine("Intent: {0}", result.Intent);
Console.WriteLine("Links:");
foreach (LinkDescription link in result.Links)
{
Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
}
AmountWithBreakdown amount = result.PurchaseUnits[0].Amount;
Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);
return response;
}
/*
Method to generate sample create order body with CAPTURE intent
#return OrderRequest with created order request
*/
private static OrderRequest BuildRequestBody(decimal totalPrice, List<SanitizeProduct> lineItems)
{
OrderRequest orderRequest = new OrderRequest()
{
Intent = "CAPTURE",
ApplicationContext = new ApplicationContext
{
BrandName = "12345",
UserAction = "CONTINUE",
},
PurchaseUnits = new List<PurchaseUnitRequest>
{
new PurchaseUnitRequest{
ReferenceId = "PUHF",
Description = "Customisable Goods",
CustomId = "CUST-HighFashions",
SoftDescriptor = "HighFashions",
Amount = new AmountWithBreakdown
{
CurrencyCode = "SGD",
Value = "230.00",
Breakdown = new AmountBreakdown
{
// The subtotal for all items (quantity * price)
ItemTotal = new Money
{
CurrencyCode = "SGD",
Value = "230.00"
},
}
},
// How do i dynamically generate the list of items instead of hardcoding it?
Items = new List<Item>
{
new Item
{
Name = "T-shirt",
Description = "Green XL",
Sku = "sku01",
UnitAmount = new Money
{
CurrencyCode = "SGD",
Value = "90.00"
},
Tax = new Money
{
CurrencyCode = "SGD",
Value = "10.00"
},
Quantity = "1",
Category = "PHYSICAL_GOODS"
},
new Item
{
Name = "Shoes",
Description = "Running, Size 10.5",
Sku = "sku02",
UnitAmount = new Money
{
CurrencyCode = "SGD",
Value = "45.00"
},
Tax = new Money
{
CurrencyCode = "SGD",
Value = "5.00"
},
Quantity = "2",
Category = "PHYSICAL_GOODS"
}
},
}
}
};
return orderRequest;
}
I have these lists:
List<Author> MyAuthorList = new List<Author>();
List<string> BookListNo1 = new List<string>() { "The Girl with the Dragon Tattoo", "The Name of the Rose", "The Alienist", "In Cold Blood", "The Firm" };
List<string> BookListNo2 = new List<string>() { "And Then There Were None", "Mystic River", "The Shadow of the Wind", "Angels & Demons" , "The Big Sleep", "The Pelican Brief" };
List<string> BookListNo3 = new List<string>() { "One for the Money", "The Maltese Falcon", "In the Woods", "Presumed Innocent", "The Thirteenth Tale", "A is for Alibi", "Postmortem" };
List<string> BookListNo4 = new List<string>() { "Midnight in the Garden of Good and Evil", "The Strange Case of Dr. Jekyll and Mr. Hyde", "A Time to Kill", "The Historian" };
MyAuthorList.Add(new Author() { FirstName = "John", LastName = "Smith", Address = "Germany", Age = 13, NumberOfBooks = 5, EMBG = 123123, Books = BookListNo1, BankAccount = 1111, BankName = "Stupid Bank Name", BankAddress = "No One Knows" });
MyAuthorList.Add(new Author() { FirstName = "Max", LastName = "Warren", Address = "France", Age = 32, NumberOfBooks = 6, EMBG = 321321, Books = BookListNo2, BankAccount = 2222, BankName = "Stupid Bank Name", BankAddress = "Near The Bakery" });
MyAuthorList.Add(new Author() { FirstName = "Quinn", LastName = "Swanson", Address = "Russia", Age = 11, NumberOfBooks = 7, EMBG = 456456, Books = BookListNo3, BankAccount = 3333, BankName = "Stupid Bank Name", BankAddress = "On Some Desert Island" });
MyAuthorList.Add(new Author() { FirstName = "Ben", LastName = "Chaplin", Address = "Indonesia", Age = 34, NumberOfBooks = 4, EMBG = 654654, Books = BookListNo4, BankAccount = 4444, BankName = "Stupid Bank Name", BankAddress = "Moskovska 45" });
MyAuthorList.Add(new Author() { FirstName = "Jack", LastName = "Smirnoff", Address = "Germany", Age = 35, NumberOfBooks = 6, EMBG = 789789, Books = BookListNo2, BankAccount = 5555, BankName = "Stupid Bank Name 2", BankAddress = "Moskovska 452" });
Now I need to find all Authors from Germany with books that have the words "Girl" and "Blood" in them.
This is what I have tried so far:
I get all the authors from Germany like this:
var germanAuthors = MyAuthorList.Where(x => x.Address.Contains("Germany"));
..and all the books that have the words "Blood" and "Girl" in them like this:
var BooksOfAuthorsFromGermany = MyAuthorList.Where(x => x.Address.Contains("Germany")).SelectMany(y => y.Books);
List<string> words = new List<string> { "Blood", "Girl"};
var searchedListOfBooks = BooksOfAuthorsFromGermany.Where(s => words.Any(w => s.Contains(w)));
However, I can't combine these two together.
Do I need to do this in a completely different way?
Try this
var BooksOfAuthorsFromGermany = MyAuthorList
.Where(x => x.Address.Contains("Germany")
&& x.Books.Where(a => a.Contains("Girl")
|| a.Contains("Blood")).Count() > 0)
.ToList();
You can combine two query as follows ,
List<string> words = new List<string> { "Blood", "Girl"};
var AuthorList = MyAuthorList.Where(x => x.Address.Contains("Germany") && x.Books.Any(a => words.Any(w=> a.Contains(w)))).ToList();
According to your requirement you can use this
var germanAuthors = MyAuthorList.Where(x => x.Address.Contains("Germany") && x.Books.Any(y => y.Contains("Blood") && y.Contains("Girl"))).Select(Z => Z.FirstName);
var germanAuthorsWithBloodOrGirl = MyAuthorList.Where(x => x.Address.Contains("Germany") && x.Books.Any(y => y.Contains("Blood") || y.Contains("Girl"))).Select(Z => Z.FirstName);
In my MVC controller, I have the following linq query (which works fine):
var result = from li in lineItems
join r in rates on li.something = r.something
select new
{
li.something
li.somethingElse
li.another
r.something
r.somethingElse
r.rate1
r.rate2
r.rate3
r.rate4
};
return JSON(result.ToList(), JsonRequestBehavior.AllowGet);
And that generates a flat object just fine. However, what I really need is for the rates to be an object of their own, one layer deeper, like this:
{
li.something
li.somethingElse
li.another
r.something
r.somethingElse
rates = {
{id = "1", value = r.rate1}
{id = "2", value = r.rate2}
{id = "3", value = r.rate3}
{id = "4", value = r.rate4}
}
}
I'm having difficulty getting the C# syntax right to make that happen. Hardcoding the id is fine. I will always only have rate 1 2 3 and 4.
You can define 'rates' property as anonymous array of object, please see below sample for reference.
{
li.something,
li.somethingElse,
li.another,
r.something,
r.somethingElse,
rates = new[]{
new {id = "1", value = r.rate1},
new {id = "2", value = r.rate2},
new {id = "3", value = r.rate3},
new {id = "4", value = r.rate4}
}
}
I ended up doing this:
rates = new
{
Rate1 = new {id = "1", value = r.rate1}
Rate2 = new {id = "2", value = r.rate2}
Rate3 = new {id = "3", value = r.rate3}
Rate4 = new {id = "4", value = r.rate4}
}
Which didn't throw any errors. It named the JSON which I didn't really need but I guess it didn't hurt anything either.
I have a JSON array and I am adding items. I want to display this JSON in a particular format.
My code:
var array = new List<object>();
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
});
array.Add(new
{
ItemName = itnme,
Price = price,
Quantity = quant,
});
This is what my array looks like. I am adding some items. Right now it produces the following output:
[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300},{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]
But i need my output like this:
[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300"},"Offers"[{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]]
That is, I need an array for offers. How can I make this possible?
Your problem appears to be that your parent object, and child "offer" objects are not related, when Offers needs to be part of the main object.
Try something like this:
var array = new List<object>();
var offers = new List<object>();
offers.Add(new
{
ItemName = itnme,
Price = price,
Quantity = quant,
});
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
Offers = offers
});
Sounds like you just want another property named "Offers"?
var array = new List<object>();
var offers = new[]
{
new {ItemName = itnme, Price = price, Quantity = quant}
...
};
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
Offers = offers // adding Offers as a property here
});
This should produce a JSON like the following:
[
{
"Dealname": "unnideal",
"Ticketcount": "25",
"OriginalPrice": "100",
"Dealsticketcount": "1",
"dealprice": "200",
"totalprice": "300",
"Offers": [
{
"ItemName": "popcorn",
"Price": "100",
"Quantity": "1"
},
{
"ItemName": "piza",
"Price": "100",
"Quantity": "1"
}
]
}
]