please I need to create a C# array with following exact format:
var sampledata = {
{Day: "Sunday", Quantity: 15},
{Day: "Monday", Quantity: 20},
{Day: "Tuesday", Quantity: 80}
}
can we create something like the above in C#. if yes, please how?
thanks...
var sampledata = new[] {
new { Day = "Sunday", Quantity = 15 },
new { Day = "Monday", Quantity = 20 },
new { Day = "Tuesday", Quantity = 80 }
};
try a Array or a List of anonymous Types (http://msdn.microsoft.com/en-US/en-en/library/bb397696.aspx)
Use object and array together?
class Order
{
public String Day;
public int Quantity;
}
Order[] orderArray = new Order[3];
orderArray[0].Date = "Sunday";
orderArray[0].Quantity = 15;
...
Related
I am trying to get into more complex Linq queries and right away catch a point I am feeling stuck. I have a following list in DB:
ID ELAPSED TIME APPISRUNNING
1 12 TRUE
2 54 TRUE
3 32 FALSE
Where ELAPSED TIME is TimeSpan and APPISRUNNING is a bool.
I would like to build a chart based on these values (https://github.com/beto-rodriguez/LiveCharts2). Chart build fine with this:
Title = "Analytics";
this.ActivityChartSeries = new ISeries[]
{
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
};
Now I somehow need to first GroupBy bool and then select a new List? I have tried following:
IEnumerable<DataRecord> dataRecords = await this.DataStore.GetItemsAsync();
this.ActivityChartSeries = dataRecords
.GroupBy(g => g.AppIsRunning)
.Select(m => new
{ // BELOW IS TOTALLY UNCLEAR FOR ME
Values = m.Select(r => r.EngineElapsed.Ticks),
Name = m.Select(r => r.Name),
})
.Select(x =>
new PieSeries<double>
{
Values = new List<double> { x.Values.FirstOrDefault() },
Name = x.Name.FirstOrDefault(),
});
Type of assigned variable:
public IEnumerable<ISeries> ActivityChartSeries
This part is totally unclear for me:
Values = m.Select(r => r.EngineElapsed.Ticks),
Name = m.Select(r => r.Name),
How after GroupBy I can create two types of data? Basically I need
"Application Running" and "Values"
"Application is not Running" and "Values"
EDIT:
Code provided by Somar Zein compiles fine:
var results = activityChartSeries
.GroupBy(a=> a.AppIsRunning)
.Select(item=> new PieSeries<double>{
Name = item.Key ? "Application is Running" : "Application is not Running",
Values = item.Select(x=> Convert.ToDouble(x.ElapsedTime.Ticks)).ToList()
});
However as a result I am getting something like this, why it is reloading in a loop?
Here is result:
enter image description here
EDIT2:
So I have created an example for testing purposes:
Class:
public class DataModel
{
public int Id { get; set; }
public TimeSpan ElapsedTime { get; set; }
public bool AppIsRunning { get; set; }
}
Code:
List<DataModel> records = new List<DataModel>();
records.Add(new DataModel { Id = 1, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 2, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 3, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 4, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 5, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
this.ActivityChartSeries = records
.GroupBy(g => g.AppIsRunning)
.Select(item => new PieSeries<double>
{
Name = item.Key ? "Running" : "Not Running",
Values = new double[] { 2, 4 },
});
I get the same reloading effect, even thou originally provided Example from LiveCharts work fine.
you could try doing something like following:
var results = activityChartSeries
.GroupBy(a=> a.AppIsRunning)
.Select(item=> new PieSeries<double>{
Name = item.Key ? "Application is Running" : "Application is not Running",
Values = item.Select(x=> Convert.ToDouble(x.ElapsedTime.Ticks)).ToList()
});
hope that could be helpful!
I have a custom object list which has month and another int value. I am getting this list from the database. So data coming from a web service as JSON. Sometimes month is not consecutive. Sometimes some month get missing. For example if this is month 7,
then months in list may contains something like this.
{1,2,3,6,7}
so I want to add the missing months which are 4,5 ----
{1,2,3,4,5,6,7}
other value should be 0 (NEW_REC_COUNT)
My Object class
public class NewData
{
public int MONTH { get; set; }
public int NEW_REC_COUNT { get; set; }
}
Sample Json
[
{
"MONTH": 1,
"NEW_REC_COUNT": 19
},
{
"MONTH": 2,
"NEW_REC_COUNT": 5
},
{
"MONTH": 3,
"NEW_REC_COUNT": 2
},
{
"MONTH": 6,
"NEW_REC_COUNT": 9
},
{
"MONTH": 7,
"NEW_REC_COUNT": 3
}
]
You can try below approach,
Select all months (int value) from list using Select
var months = NewDataList.Select(x => x.MONTH); // This will give you all integers i.e MONTHs.
Find Max() from months and create Range from 1... maxMonths
var maxMonths = months.Max();
var oneTomaxMonths = Enumerable.Range(1,maxMonths).ToList();
Now you have 2 lists i.e. months and oneToMaxMonths, use Except to get missing Months from list of New Data
var results = oneTomaxMonths.Except(months);
Foreach result create new instance with NEW_REC_COUNT = 0
POC : .net Fiddle
If you don't have a lot of data, you can try a smiple loop and Insert omitted items into the list:
List<NewData> list = ...
// If list is not guarantee to be sorted
list.Sort((a, b) => a.MONTH.CompareTo(b.MONTH));
for (int i = 0; i < list.Count - 1; ++i) {
NewData current = list[i];
NewData next = list[i + 1];
// Do we have a hole at position i + 1?
if (current.MONTH + 1 < next.MONTH) {
list.Insert(i + 1, new NewData() {
MONTH = current.MONTH + 1, // Omitted month
NEW_REC_COUNT = 0, // Default value
});
}
}
Edit: If we want months from 1 up and including the current month (DateTime.Today.Month), we can use Linq:
using System.Linq;
...
List<NewData> list = ...
// Let's generalize a bit if you want, say Q3 period
int fromMonth = 1;
int upToMonth = DateTime.Today.Month; // or 7 for testing
list = Enumerable
.Range(fromMonth, upToMonth - fromMonth + 1)
.Select(month =>
list.FirstOrDefault(item => item.MONTH == month)
?? new NewData() { MONTH = month, // Omitted month
NEW_REC_COUNT = 0 }) // Default value
.ToList();
If you want to modify existing list:
list.AddRange(Enumerable
.Range(fromMonth, upToMonth - fromMonth + 1)
.Where(month => !list.Any(item => item.MONTH == month))
.Select(month => new NewData() {
MONTH = month,
NEW_REC_COUNT = 0 })
.ToArray());
I'm extremely new to coding, so the answer/s to this may be obvious. I have to make the card game War. I've created a list of strings like so for a part of the deck:
List<string> userDeck = new List<string>
{
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
"Ace",
};
Is there a way I can instruct the computer that "Jack" will be greater than "10", "Queen" greater than "Jack", and so on? I'm not sure where or how I should do it.
OR, if you have any other suggestions as to how I should do this, please let me know. I have to be using a list. I initially made a list of integers instead, but I wasn't aware of an uncomplicated way to assign the names such as "Jack," "Queen," "King," etc. to them for display purposes.
Any help would be greatly appreciated.
Try to create a object called "Card". This object can contain more than a value. Eg:
public class MyCard
{
public string Name {get;set;}
public int Value {get;set;}
public MyCard(string name, int value)
{
this.Name = name;
this.Value = value;
}
}
After create this object, you will use this at your list.
List<MyCard> userDeck = new List<MyCard>();
You can fill the list this way:
usertDeck.Add(new MyCard("2", 1));
....
usertDeck.Add(new MyCard("K", 11));
So, to compare 2 cards, just check using the "Value" variable
The easiest way to refactor your code (to your requirements value per card) is to use Tuple's instead of string type in generic List as follow:
List<Tuple<int,string>> userDeck = new List<Tuple<int,string>>
{
new Tuple<int,string>(2,"2"),
new Tuple<int,string>(3,"3"),
new Tuple<int,string>(4,"4"),
new Tuple<int,string>(5,"5"),
new Tuple<int,string>(6,"6"),
new Tuple<int,string>(7,"7"),
new Tuple<int,string>(8,"8"),
new Tuple<int,string>(9,"9"),
new Tuple<int,string>(10,"10"),
new Tuple<int,string>(11,"Jack"),
new Tuple<int,string>(12,"Queen"),
new Tuple<int,string>(13,"King"),
new Tuple<int,string>(14,"Ace"),
};
Similar to Vincius's answer but with some changes for better usability:
enum Suit
{
Clubs = 1,
Diamonds = 2,
Hearts = 3,
Spades = 4
}
class Card
{
private static readonly Dictionary<string, int> rankMap = new Dictionary<string, int>()
{
{"2", 2 },
{"3", 3 },
{"4", 4 },
{"5", 5 },
{"6", 6 },
{"7", 7 },
{"8", 8 },
{"9", 9 },
{"10", 10 },
{"Jack", 11 },
{"Queen", 12 },
{"King", 13 },
{"Ace", 14 },
};
private Suit suit;
private string rank;
public Suit Suit => suit;
public string Rank => rank;
public int Value { get { return rankMap[rank]; } }
public Card(Suit s, string r)
{
suit = s;
rank = r;
}
}
The way you can use it:
Card c1 = new Card(1, "Jack"); // 1 is Clubs
Card c2 = new Card(4, "Queen"); // 4 is Spades
Console.WriteLine(c1.Value); // prints 11
Console.WriteLine(c2.Value); // prints 12
I am have an list of object. Which has 4 properties. Month, Category, 2015 & 2014
Month Category 2015 2014
Jan A 10 100
Jan B 20 200
Jan C 30 300
Jan D 40 400
Feb B 50 500
Feb C 60 600
Feb D 70 700
Mar A 80 800
Mar I 90 900
Mar J 100 1000
I want to group the values using month and I want to generate JSON output like this. I am creating property in JSON object by prefixing cur & pre keywords to category name & the value they represents comes from 2014 and 2015 years
[{
name: "jan",
curA: 10,
preA: 100,
curB: 20,
preB: 200,
curC: 30,
preC: 400,
curD: 40,
preD: 400
}, {
name: "feb",
curB: 50,
preB: 500,
curC: 60,
preC: 600,
curD: 70,
preD: 700
}, {
name: "mat",
curA: 80,
preA: 800,
curI: 90,
preI: 900,
curJ: 100,
preJ: 1000
}]
I can use JSON.NET to serialize C# object into JSON but I am struggling to create a class which can be converted into required format.
You can use an array of dictionaries.
var list = new List<Dictionary<string, int>> ();
You'll have to figure out how you want to populate your dictionaries based on the data but you'll need to do this for as many months / segmentation points that you wish:
var data = new Dictionary<string, int>
{
{ "name", 10 },
{ "curA", 100 },
{ "preA", 20 } // And so on...
};
list.Add(data);
And then you can convert your list to json in a similar manner:
string json = JsonConvert.SerializeObject(points, Formatting.Indented);
Hope this helps!
EDIT: Original question was asking for help converting his source list into the desired list in the JSON string.
Without knowing the format of your source list (objects, datarows, etc) I made an assumption that you just have a list of objects. My object look like this:
public class ListRow {
public string Month { get; set; }
public string Category { get; set; }
public string _2015 { get; set; }
public string _2014 { get; set; }
}
I'm also assuming you have a variable called list which contains a list of those objects. An unpopulated definition looks like:
var list = new List<ListRow> ();
I quickly put this untested code together as a guide on how you could go about converting your source list into the new format.
var convertedList = new List<Dictionary<string, string>> ();
var groupedList = list.GroupBy (_ => _.Month);
foreach (var item in groupedList) {
var data = new Dictionary<string, string> ();
data.Add ("name", item.Key);
foreach (var value in item) {
data.Add (string.Format ("cur{0}", value.Category), value._2015);
data.Add (string.Format ("pre{0}", value.Category), value._2014);
}
convertedList.Add (data);
}
And then you'll want to serialize the convertedList variable.
Hope this gets you closer to your solution.
Here is my implementation :
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
public class Transactions
{
public string Month { get; set; }
public string Cath { get; set; }
public string Year { get; set; }
public int Unit { get; set; }
}
class Program
{
static void Main(string[] args)
{
var transactionsList = new List<Transactions>();
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "A", Year = "pre", Unit = 10 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "A", Year = "cur", Unit = 100 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "B", Year = "pre", Unit = 20 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "B", Year = "cur", Unit = 200 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "C", Year = "pre", Unit = 30 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "C", Year = "cur", Unit = 300 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "D", Year = "pre", Unit = 40 });
transactionsList.Add(new Transactions() { Month = "Jan", Cath = "D", Year = "cur", Unit = 400 });
transactionsList.Add(new Transactions() { Month = "Feb", Cath = "B", Year = "pre", Unit = 50 });
transactionsList.Add(new Transactions() { Month = "Feb", Cath = "B", Year = "cur", Unit = 500 });
var transactionsQuery =
(from t in transactionsList
group t by t.Month into newGroup
orderby newGroup.Key descending
select newGroup).ToList();
var dictionaryList = new List<Dictionary<string, object>>();
foreach (var nameGroup in transactionsQuery)
{
var data = new Dictionary<string, object>();
data.Add("name", nameGroup.Key);
foreach (var item in nameGroup)
{
data.Add(string.Format("{0}{1}", item.Year, item.Cath), item.Unit);
}
dictionaryList.Add(data);
}
var ser = JsonConvert.SerializeObject(dictionaryList);
Console.WriteLine(ser);
Console.ReadLine();
}
}
}
I am using a ListBox and the data is a class:
private class Duration
{
public int Value { get; set; }
public string Label { get; set; }
}
I bind the class in this way:
var durations = new List<Duration>()
{
new Duration() { Value = 5, Label = "5 minutes" },
new Duration() { Value = 10, Label = "10 minutes" },
new Duration() { Value = 15, Label = "15 minutes" },
new Duration() { Value = 30, Label = "30 minutes" },
new Duration() { Value = 45, Label = "45 minutes" },
new Duration() { Value = 60, Label = "1 hour" },
new Duration() { Value = 90, Label = "1 hour and half" }
};
this.listTime.DataSource = durations;
this.listTime.DisplayMember = "Label";
this.listTime.ValueMember = "Value";
Everything works fine and the labels are show.
When i go to read the selected value, I am not able to recover the value of the selected item.
I was expecting to be able to do this:
int value = listTime.SelectedItems[0].Value;
or at least this:
Duration value = listTime.SelectedItems[0];
but this gives me error, what I am doing wrong? How is the right way to get the value of the selected item on the ListBox?
if (listTime.SelectedIndex != -1)
{
var item = listTime.SelectedItem as Duration;
//or as suggested by 'Stu'
var item = (Duration)listTime.SelectedItem;
MessageBox.Show(item.Value.ToString());
}
If you use Listbox this code is Ok:
listTime.Items[0].Value