How can I deserialize and display these instances - c#

I created these instances for coffee types and in final I want to deserialize them and display them per instance. I created a foreach loop but it gives me a lot of repeated data and If possible I want to display data instance per instance.
Is there something else that I can use to display them?
public void CoffeeTypes()
{
Coffee coffeeType1 = new Coffee()
{
CoffeeID = "321",
CoffeePrice = 1.50,
TSpoonsSugar = 'N',
CoffeeAmountRatio = 1,
MilkAmountRatio = 0,
Size = 'S'
};
Coffee coffeeType2 = new Coffee()
{
CoffeeID = "322",
CoffeePrice = 2.99,
TSpoonsSugar = 'N',
CoffeeAmountRatio = 1,
MilkAmountRatio = 0,
Size = 'M'
};
Coffee coffeeType3 = new Coffee()
{
CoffeeID = "323",
CoffeePrice = 4.50,
TSpoonsSugar = 'N',
CoffeeAmountRatio = 1,
MilkAmountRatio = 0,
Size = 'L'
};
Coffee coffeeType4 = new Coffee()
{
CoffeeID = "413",
CoffeePrice = 1.99,
TSpoonsSugar = 'Y',
CoffeeAmountRatio = 1,
MilkAmountRatio = 0,
Size = 'S'
};
List<Coffee> coffeeData = new List<Coffee>()
{
coffeeType1,
coffeeType2,
coffeeType3,
coffeeType4
};
Coffee.SerializeData(coffeeData, filePath);
List<Coffee> coffeePosibilities = Coffee.DeserializeData<Coffee>(filePath);
Coffee.coffeeInstance = coffeePosibilities;
foreach (var coffee in coffeePosibilities)
{
Console.WriteLine("Coffee Type 1 : Coffee ID: " + coffee.CoffeeID);
Console.WriteLine("Coffee Type 2 : Coffee ID: " + coffee.CoffeeID);
Console.WriteLine("Coffee Type 3 : Coffee ID: " + coffee.CoffeeID);
Console.WriteLine("Coffee Type 4 : Coffee ID: " + coffee.CoffeeID);
}

Change your foreach loop to output information for your current element only
foreach (var coffee in coffeePosibilities)
{
Console.WriteLine($"Coffee Type : Coffee ID: {coffee.CoffeeID}");
}

Related

EPPlus Pivot table SubTotalFunctions produces spreadsheet error

I am creating a pivot table to with data. I create a RowField and attempt to add a SubTotalFunctions to that field.
When I open the .xlsx file, I get an error that says the file needs to be repaired.
Is this a bug or is there another option that I should be setting?
using OfficeOpenXml;
using OfficeOpenXml.Table.PivotTable;
var data = Datas();
var stream = new FileStream("Data.xlsx", FileMode.Create);
// Create the spread sheet package
var pkg = new ExcelPackage(stream);
var wsData = pkg.Workbook.Worksheets.Add("Data");
var wsPivot = pkg.Workbook.Worksheets.Add("Pivot Table");
var dataRange = wsData.Cells["A1"].LoadFromCollection(data, true);
// Create the pivot table
var pivotTable = wsPivot.PivotTables.Add(wsPivot.Cells["A1"], wsData.Cells[1,1,dataRange.End.Row, 3], "Pivot Table");
pivotTable.DataFields.Add(pivotTable.Fields[0]); // FirstNumber
var r = pivotTable.RowFields.Add(pivotTable.Fields[1]); // SecondNumber
pivotTable.ColumnFields.Add(pivotTable.Fields[2]); // Text
r.SubtotalTop = true;
r.SubTotalFunctions = eSubTotalFunctions.Sum;
r.Sort = eSortType.Ascending;
r.Compact = true;
r.Outline = true;
pkg.Save();
stream.Flush();
stream.Close();
IEnumerable<Data> Datas()
{
return new List<Data>
{
new()
{
Text = "red",
FirstNumber = 0,
SecondNumber = 10
},
new()
{
Text = "red",
FirstNumber = 1,
SecondNumber = 10
},
new()
{
Text = "blue",
FirstNumber = 2,
SecondNumber = 10
},
new()
{
Text = "blue",
FirstNumber = 3,
SecondNumber = 20
},
new()
{
Text = "green",
FirstNumber = 4,
SecondNumber = 20
},
new()
{
Text = "green",
FirstNumber = 5,
SecondNumber = 40
}
};
}
internal class Data
{
public int FirstNumber { get; set; }
public int SecondNumber { get; set; }
public string Text { get; set; }
}

How to fill picker with a list

I am updating older code but part of it must stay the same. I have now picker that needs to be filled with list.
My list
public List<TimeoutBetweenSentences> FillTimoutOptions()
{
var newListTimeoutBetweenSentenceses = new List<TimeoutBetweenSentences>()
{
new TimeoutBetweenSentences()
{
Position = 0,
Text = "+ 0 sekund",
Value = 0
},
new TimeoutBetweenSentences()
{
Position = 1,
Text = "+ 1 sekunda",
Value = 1
},
new TimeoutBetweenSentences()
{
Position = 2,
Text = "+ 2 sekundy",
Value = 2
},
new TimeoutBetweenSentences()
{
Position = 3,
Text = "+ 3 sekundy",
Value = 3
},
new TimeoutBetweenSentences()
{
Position = 4,
Text = "+ 4 sekundy",
Value = 4
},
new TimeoutBetweenSentences()
{
Position = 5,
Text = "+ 5 sekund",
Value = 5
},
};
return newListTimeoutBetweenSentenceses;
}
List<TimeoutBetweenSentences> allOptions = FillTimoutOptions();
sentencePausesStepper.Items.Add(allOptions.Select(m => m.Text).ToList().ToString());
however this displays just as "System collections" DO zou have any idea?
this is adding an entire list as ONE element
sentencePausesStepper.Items.Add(allOptions.Select(m => m.Text).ToList().ToString());
to add elements of one list to another, use AddRange instead
sentencePausesStepper.Items.AddRange(allOptions.Select(m => m.Text).ToList().ToString());
or better, do this
sentencePausesStepper.ItemsSource = allOptions;
sentencePausesStepper.ItemDisplayBinding = new Binding("Text");

c# filling up empty records

need some help with my foreach to recongonize the empty record and fill the gap with "-";
let's say we have 30min, 45min, 90min, 120min and not 60min in the case:
It can count the total records of each id, let's say the maximum is 5, 30min, 45min, 60min, 90min and 120min.
if there are 3, then it could check which is missing and than can fill with "-".
Same ideia of the script.
List<Treatment> treatment = new List<Treatment>();
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "30", price = 30 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "45", price = 45 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "60", price = 60 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "30", price = 30 });
//treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "45", price = 45 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "60", price = 60 });
var newList = (from t in treatment
select t)
.AsQueryable().ToList();
List<List> newList= new List<List>();
foreach (var item in newList)
{
if (item.duration == "30")
{
newList.Add(new List { treatmentNameId = item.treatmentNameId, thirtyMin = "30" });
}
if (item.duration == "45")
{
newList.Add(new List { treatmentNameId = item.treatmentNameId, fortyFive= "45" });
}
if (item.duration == "60")
{
newList.Add(new List { treatmentNameId = item.treatmentNameId, sixty= "60" });
}
}
The end result should like something as,
id:1 30, 45, 60, -
id:2 30, - , 60, 90
id:3 - , 45, -, 90
etc...
Many many thanks for the help.
I'm not going to provide a very detailed explanation of all this, but conceptually I'm just grouping by treatmentNameId and then doing something very similar to an outer join in SQL. If the group join comes up empty for the duration, I'm selecting '-' instead of the duration. Using anonymous types for brevity.
var durations = new[] {"15", "30", "45", "60"};
var results = treatments
.GroupBy(t => t.treatmentNameId).Select(group => new
{
treatmentNameId = group.Key,
durations = durations.GroupJoin(group, s => s, g => g.duration,
(s, grouping) => !grouping.Any() ? "-" : s)
});
foreach (var result in results)
{
Console.WriteLine(result.treatmentNameId + ": " + string.Join(", ", result.durations));
}
This results in:
11: -, 30, 45, 60
2: -, 30, -, 60
If you have problems with something more specific, I'd be happy to explain further.

C# dynamic tree with many parameters, how to do it?

I am trying to fill a tree with more than one parameter (points and types) and at the end, show which "branch" has the max of points and in every branch, show how many equal tupe I have.
The tree will be something like this:
FATHER (Points:200|Type:2)
|_CHILD01 (P:120|Type:3)
| |_CHILD4 (P:300|T:3)
| | |_CHILD8 (P:220|T:3)
| | |_CHILD9 (P:65|T:1)
| |_CHILD5 (P:15|T:9)
|_CHILD2 (P:10|T:1)
|_CHILD3 (P:80|T:2)
|_CHILD6 (P:25|T:2)
| |_CHILD10 (P:110|T:7)
| |_CHILD11 (P:195|T:3)
|_CHILD7 (P:50|T:7)
and what I am trying to get is:
NUMBER OF POINTS PER BRANCH:
Branch01 -> FATHER (200), CHILD01 (120), CHILD04 (300), CHILD08 (220) -> TotalPoints: 840
Branch02 -> FATHER (200), CHILD01 (120), CHILD04 (300), CHILD09 (65) -> TotalPoints: 685
Branch03 -> FATHER (200), CHILD01 (120), CHILD05 (15) -> TotalPoints: 335
Branch04 -> FATHER (200), CHILD02 (10) -> TotalPoints: 210
Branch05 -> FATHER (200), CHILD03 (80), CHILD06 (25), CHILD10 (110) -> TotalPoints: 415
Branch06 -> FATHER (200), CHILD03 (80), CHILD06 (25), CHILD11 (195) -> TotalPoints: 500
Branch07 -> FATHER (200), CHILD03 (80), CHILD07 (50) -> TotalPoints: 330
and
COUNT THE NUMBER OF TYPES in WHICH BRANCH:
TypePerBranch01:
- Type1:0
- Type2:1
- Type3:2
- Type4:1
- Type5:0
- Type6:0
- Type7:0
- Type8:0
- Type9:0
TypePerBranch02:
- Type1:1
- Type2:1
- Type3:1
- Type4:1
- Type5:0
- Type6:0
- Type7:0
- Type8:0
- Type9:0
TypePerBranch03:
- Type1:0
- Type2:1
- Type3:1
- Type4:0
- Type5:0
- Type6:0
- Type7:0
- Type8:0
- Type9:1
TypePerBranch04:
- Type1:1
- Type2:1
- Type3:0
- Type4:0
- Type5:0
- Type6:0
- Type7:0
- Type8:0
- Type9:0
TypePerBranch05:
- Type1:0
- Type2:3
- Type3:0
- Type4:0
- Type5:0
- Type6:0
- Type7:1
- Type8:0
- Type9:0
TypePerBranch06:
- Type1:0
- Type2:3
- Type3:1
- Type4:0
- Type5:0
- Type6:0
- Type7:0
- Type8:0
- Type9:0
TypePerBranch07:
- Type1:0
- Type2:2
- Type3:0
- Type4:0
- Type5:0
- Type6:0
- Type7:1
- Type8:0
- Type9:0
I have done some code but its not working.
Here´s the function:
//
// FUNÇÃO ResizeArray
public T[,] ResizeArray<T>(T[,] original, int xSize, int ySize)
{
var newArray = new T[xSize, ySize];
var xMin = Math.Min(xSize, original.GetLength(0));
var yMin = Math.Min(ySize, original.GetLength(1));
for (var x = 0; x < xMin; x++)
for (var y = 0; y < yMin; y++)
newArray[x, y] = original[x, y];
return newArray;
}
//
// FUNÇÃO TreeBranchPath
int[] TotalPontosRamo = new int[1];
int[,] FolhaInfoPontos = new int[1, 1];
int[,] FolhaInfoPatamar = new int[1, 1];
int CountRamos = 0;
private void TreeBranchPath(int idusr, int usrpnts, int usrpata, int nivelnum, int ramonum)
{
FolhaInfoPontos[nivelnum, ramonum] = usrpnts;
FolhaInfoPatamar[nivelnum, ramonum] = usrpata;
var AfilhadosList = (from af in db.NRV_USERS
where af.idpatrocinador == idusr
select af).ToList();
/*Se for NULL não tem descendentes */
if (AfilhadosList != null)
{
int CountNumFilhos = AfilhadosList.Count();
int CountFilhos = 0;
nivelnum = nivelnum + 1;
FolhaInfoPontos = ResizeArray(FolhaInfoPontos, nivelnum, ramonum + CountNumFilhos);
FolhaInfoPatamar = ResizeArray(FolhaInfoPatamar, nivelnum, ramonum + CountNumFilhos);
foreach (var descid in AfilhadosList)
{
CountFilhos = CountFilhos + 1;
/* Inicio - Quantos Pontos o User tem */
var UserPoints = (from pnt in db.NRV_USERPONTOS
where pnt.iduser == descid.id_user && pnt.usrpntact == true
select pnt).FirstOrDefault();
int TotalUserPoints = UserPoints.pontosgrupo + UserPoints.pontosproprios;
/* Fim - Quantos Pontos o User tem */
TotalPontosRamo[CountRamos] = TotalPontosRamo[CountRamos] + TotalUserPoints;
/* Inicio - Em que Patamar o User está */
var AuxUserPatamar = (from cp in db.NRV_USERPATAMAR
where cp.iduser == idusr
select cp.idpatamax).FirstOrDefault();
/* Fim - Em que Patamar o User está */
Array.Resize(ref TotalPontosRamo, CountRamos + 1);
TreeBranchPath(descid.id_user, TotalUserPoints, AuxUserPatamar, nivelnum, CountFilhos);
}
}
else
{
return;
}
}
Can someone help me?
Here I indented the results based on the level of the Node.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Node father = new Node()
{
name = "FATHER", points = 200, type = 2, children = new List<Node>(){
new Node() {
name = "CHILD01", points = 120, type = 3, children = new List<Node>(){
new Node(){
name = "CHILD04", points = 300, type = 3, children = new List<Node>(){
new Node(){ name = "CHILD08", points = 220, type = 3, children = null},
new Node(){ name = "CHILD09", points = 65, type = 1, children = null}
}
},
new Node(){ name = "CHILD05", points = 15, type = 9, children = null}
}
},
new Node() { name = "CHILD02", points = 10, type = 1, children = null},
new Node(){
name = "CHILD03", points = 80, type = 2, children = new List<Node>(){
new Node(){
name = "CHILD06", points = 25, type = 2, children = new List<Node>(){
new Node(){ name = "CHILD10", points = 110, type = 7, children = null},
new Node(){ name = "CHILD11", points = 195, type = 3, children = null}
}
},
new Node(){ name = "CHILD07", points = 50, type = 7, children = null}
}
}
}
};
Count results = father.GetTotals(0);
foreach (Count result in Node.results)
{
Console.WriteLine("{0} Name = {1}, Points = {2}, Types = {3}",
string.Join("", Enumerable.Repeat(" ", result.level)),
result.name,
result.points,
string.Join(",", result.types.OrderBy(x => x.Key).Select(x => x.Key.ToString() + ":" + x.Value.ToString()).ToArray())
);
}
}
}
public class Count
{
public string name;
public int level { get; set; }
public int points { get; set; }
public Dictionary<int, int> types { get; set; }
}
public class Node
{
public string name { get; set; }
public int points { get; set; }
public int type { get; set; }
public List<Node> children { get; set; }
public static List<Count> results = new List<Count>();
public Count GetTotals(int level)
{
Count result = new Count();
result.name = name;
result.level = level;
result.points = points;
result.types = new Dictionary<int, int>();
result.types.Add(type, 1);
if (children != null)
{
for (int childCount = children.Count - 1; childCount >= 0; childCount--)
{
Node child = children[childCount];
Count childResutls = child.GetTotals(level + 1);
result.points += childResutls.points;
foreach (int key in childResutls.types.Keys)
{
if (result.types.ContainsKey(key))
{
result.types[key] += childResutls.types[key];
}
else
{
result.types.Add(key, childResutls.types[key]);
}
}
}
}
Node.results.Insert(0, result);
return result;
}
}
}
​
Here is a slightly different answer with the nodes in the same order as the input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Node father = new Node()
{
name = "FATHER", points = 200, type = 2, children = new List<Node>(){
new Node() {
name = "CHILD01", points = 120, type = 3, children = new List<Node>(){
new Node(){
name = "CHILD04", points = 300, type = 3, children = new List<Node>(){
new Node(){ name = "CHILD08", points = 220, type = 3, children = null},
new Node(){ name = "CHILD09", points = 65, type = 1, children = null}
}
},
new Node(){ name = "CHILD05", points = 15, type = 9, children = null}
}
},
new Node() { name = "CHILD02", points = 10, type = 1, children = null},
new Node(){
name = "CHILD03", points = 80, type = 2, children = new List<Node>(){
new Node(){
name = "CHILD06", points = 25, type = 2, children = new List<Node>(){
new Node(){ name = "CHILD10", points = 110, type = 7, children = null},
new Node(){ name = "CHILD11", points = 195, type = 3, children = null}
}
},
new Node(){ name = "CHILD07", points = 50, type = 7, children = null}
}
}
}
};
Count results = father.GetTotals();
foreach (Count result in Node.results)
{
Console.WriteLine("Name = {0}, Points = {1}, Types = {2}",
result.name,
result.points,
string.Join(",", result.types.OrderBy(x => x.Key).Select(x => x.Key.ToString() + ":" + x.Value.ToString()).ToArray())
);
}
}
}
public class Count
{
public string name;
public int points { get; set; }
public Dictionary<int, int> types { get; set; }
}
public class Node
{
public string name { get; set; }
public int points { get; set; }
public int type { get; set; }
public List<Node> children { get; set; }
public static List<Count> results = new List<Count>();
public Count GetTotals()
{
Count result = new Count();
result.name = name;
result.points = points;
result.types = new Dictionary<int, int>();
result.types.Add(type, 1);
if (children != null)
{
for (int childCount = children.Count - 1; childCount >= 0; childCount--)
{
Node child = children[childCount];
Count childResutls = child.GetTotals();
result.points += childResutls.points;
foreach (int key in childResutls.types.Keys)
{
if (result.types.ContainsKey(key))
{
result.types[key] += childResutls.types[key];
}
else
{
result.types.Add(key, childResutls.types[key]);
}
}
}
}
Node.results.Insert(0, result);
return result;
}
}
}
​

Group by using linq (range + count)

var data = new[] {
new { Id = 0, Cat = 1, Price = 2 },
new { Id = 1, Cat = 1, Price = 10 },
new { Id = 2, Cat = 1, Price = 30 },
new { Id = 3, Cat = 2, Price = 50 },
new { Id = 4, Cat = 2, Price = 120 },
new { Id = 5, Cat = 2, Price = 200 },
new { Id = 6, Cat = 2, Price = 1024 },
};
var ranges = new[] { 10, 50, 100, 500 };
Needed output is grouped price count by equal or greater than the range used according categories.
(in one linq statement)
cat range count
-------------------------------------
1 10 2 (In 1. categories there is 2 item that price >= 10(range) [10;30])
2 10 4 (In 2. categories there is 4 item that price >= 10(range) [50;120;200;1024])
2 50 4 ....
2 100 3 ....
2 500 1 (In 2. categories there is 1 item that price >= 500(range) [1024])
Try this:
var data = new[] {
new { Id = 0, Cat = 1, Price = 2 },
new { Id = 1, Cat = 1, Price = 10 },
new { Id = 2, Cat = 1, Price = 30 },
new { Id = 3, Cat = 2, Price = 50 },
new { Id = 4, Cat = 2, Price = 120 },
new { Id = 5, Cat = 2, Price = 200 },
new { Id = 6, Cat = 2, Price = 1024 },
};
var ranges = new[] { 10, 50, 100, 500 };
var result = from r in ranges
from g in data
where g.Price >= r
select new {g.Cat, Price=r};
var groupedData =
from d in result
group d by new{d.Cat, d.Price} into g
select new{Cat=g.Key.Cat, Price=g.Key.Price, TotalCount=g.Count()};
This should work:
var values =
data.SelectMany(x => ranges.Where(y => x.Price >= y)
.Select(y => new { Record = x, Range = y }))
.GroupBy(x => new { Cat = x.Record.Cat, Range = x.Range })
.Select(x => new { Cat = x.Key.Cat, Range = x.Key.Range, Count = x.Count()});
Results:
{ Cat = 1, Range = 10, Count = 2 }
{ Cat = 2, Range = 10, Count = 4 }
{ Cat = 2, Range = 50, Count = 4 }
{ Cat = 2, Range = 100, Count = 3 }
{ Cat = 2, Range = 500, Count = 1 }

Categories

Resources