Creating a json-style inside a linq select statement - c#

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.

Related

Joining List of item

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.

C# Unity3D initialize List<T> on declaration only initializes two items when there are four?

Initializing four items into a List as follows, BUT it only initializes the first two items ... I really can't see what is wrong with this?
public List<SceneStore> lcRecordList = new List<SceneStore>
{
new SceneStore { description ="Jill ", ID = 1, visited = false },
new SceneStore { description = "Jack", ID = 2, visited = false},
new SceneStore { description = "Joe", ID = 3, visited = false},
new SceneStore { description = "Jenny", ID = 4, visited = false}
};
void NetTest()
{
NetworkService lcMyNetworkService = new NetworkService();
lcMyNetworkService.PutJsonList <SceneStore>(lcRecordList, "https://NewSimland.com/~todd/JSON", ReceiveAListOfRecords);
}
Took a screenshot
This adds four items just fine:
public List<SceneStore> lcRecordList;
void NetTest()
{
NetworkService lcMyNetworkService = new NetworkService();
lcRecordList = new List<SceneStore>
{
new SceneStore { description ="Jill ", ID = 1, visited = false },
new SceneStore { description = "Jack", ID = 2, visited = false},
new SceneStore { description = "Joe", ID = 3, visited = false},
new SceneStore { description = "Jenny", ID = 4, visited = false}
};
lcMyNetworkService.PutJsonList <SceneStore>(lcRecordList, "https://NewSimland.com/~todd/JSON", ReceiveAListOfRecords);
}
So why is initialization of lcRecordList on declaration limited to the first two?
Took another screenshot of the local variable value:
As indicated by CaTS and Mo Narimani, the UNITY3D environment is initializing the values based on the first time the list was initialized because it found a Public class attribute (aka variable) in the MonoBehaviour. That was overriding the initialization in the script after more items were added in the script code.
SO the Answer is to "refresh" that by clicking on Reset in the Inspector after adding more items , when changing the initialization on declaration, that works!!
See screenshot here:
Unity3D sticks with the first initialization?
try this instead:
public List<SceneStore> lcRecordList = new List<SceneStore>
{
SceneStore store;
store= new SceneStore { description ="Jill ", ID = 1, visited = false },
lcRecordLisr.Add(store);
store= new SceneStore { description = "Jack", ID = 2, visited = false},
lcRecordLisr.Add(store);
store= new SceneStore { description = "Joe", ID = 3, visited = false},
lcRecordLisr.Add(store);
store= new SceneStore { description = "Jenny", ID = 4, visited = false}
lcRecordLisr.Add(store);
};

Issue regarding json array

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"
}
]
}
]

Dynamic linq query with nested groups

I'm trying to create nested group with dynamic query.
Following are my collection of data
var invoices = new List < Purchase > () {
new Purchase() {
Id = 1, Customer = "a", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 2, Customer = "a", Date = DateTime.Parse("1/2/2009")
}, new Purchase() {
Id = 3, Customer = "a", Date = DateTime.Parse("1/2/2009")
}, new Purchase() {
Id = 4, Customer = "b", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 5, Customer = "b", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 6, Customer = "b", Date = DateTime.Parse("1/2/2009")
}
};
This linq query is returning the desired result.
var tree = invoices.GroupBy(x => x.Date).Select(x => new
{
Key = x.Key,
Items = x.GroupBy(y => y.Customer).Select(y => new
{
Key = y.Key,
Items = y
})
}).ToList();
Below is the output of the above linq query
But I just need to group different columns in different order.
So that I try to create dynamic linq query. But my code block result not same as my previous linq query.
var groupedInvoiceItems = invoices.AsQueryable().GroupBy("new (Date, Customer)", "it");
You could do this with Generics. Just Pass in your Lambda to a generic method.
Something like:
private IEnumerable<PurchaseGrp> BuildList<TSource>(IQueryable<TSource> allRecords,
Func<TSource, string> selector)
{
var result = allRecords.GroupBy(x = > x.selector(x));
return result;
}
The return type could be a new Grouped type PurchaseGrp or the same as your source (Purchase).

MVC DropDownList selected value not working

I am using MVC 5.
I have my ViewBag for list as
ViewBag.TitleList = new SelectList((new string[] { "Mr", "Miss", "Ms", "Mrs" }), contact.Title);
//contact.Title has selected value.
then I tried converting the array to SelectListItem ( to no avail)
On the View it looks like
#Html.DropDownListFor(model => model.Title, ViewBag.TitleList as SelectList, "Select")
also I tried
#Html.DropDownList("Title", ViewBag.TitleList as SelectList, "Select")
The list loads successfully but the Selected Value is Not selected.
How to Fix this problem?
Update
The culprit was ViewBag.Title matching my model.Title. Renamed my model property to something else and it worked. Arrgh!
Set value of the Title property in the controller:
ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" });
viewModel.Title = "Miss"; // Miss will be selected by default
Another possible reason (and the correct one, based on the comments below) is that ViewData["Title"] is overridden by another value. Change name of the Title property to any other and everything should work.
When a value is not specified (i.e. "Id"), DropDownListFor sometimes does not behave properly. Try this:
public class FooModel
{
public int Id { get; set; }
public string Text { get; set; }
}
var temp = new FooModel[]
{
new FooModel {Id = 1, Text = "Mr"}, new FooModel {Id = 2, Text = "Miss"},
new FooModel {Id = 3, Text = "Ms"}, new FooModel {Id = 4, Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Id", "Text", 2);
EDIT: other sololution
var temp = new []
{
new SelectListItem {Value = "Mr", Text = "Mr"}, new SelectListItem {Value = "Miss", Text = "Miss"},
new SelectListItem {Value = "Ms", Text = "Ms"}, new SelectListItem {Value = "Mrs", Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Value", "Text", "Miss");

Categories

Resources