I would like to make a method to print a LINQ (table) with all its properties and values to the console.
I'm currently trying to do this via the System.Reflection.GetType().GetProperties()
What I think is going wrong is the type of parameter I try to send to the method. If possible this should be a var so I can use this method with any class list. (not sure if this is possible)
The issue is with the printtabel() method.
I started from:
Print a table with LINQ
namespace LINQ
{
class Program
{
public class Bier
{
public int BierNr { get; set; }
public string Biernaam { get; set; }
public float Alcohol { get; set; }
public Brouwer Brouwer { get; set; } //associatie met een brouwer
public override string ToString() { return Biernaam + ": " + Alcohol + "% alcohol"; }
}
public class Brouwer
{
public int BrouwerNr { get; set; }
public string Brouwernaam { get; set; }
public bool Belgisch { get; set; }
public List<Bier> Bieren { get; set; }
public override string ToString() { return "Brouwerij " + Brouwernaam + " (" + (Belgisch ? "Belgisch" : "Niet Belgisch") + ")"; }
}
public class Brouwers
{
public List<Brouwer> GetBrouwers()
{
List<Brouwer> lijst = new List<Brouwer>();
Brouwer palm = new Brouwer { BrouwerNr = 1, Brouwernaam = "Palm", Belgisch = true };
palm.Bieren = new List<Bier> {
new Bier {BierNr=1,Biernaam="Palm Dobbel", Alcohol=6.2F, Brouwer=palm},
new Bier {BierNr=2, Biernaam="Palm Green", Alcohol=0.1F, Brouwer=palm},
new Bier {BierNr=3, Biernaam="Palm Royale", Alcohol=7.5F, Brouwer=palm}
};
lijst.Add(palm);
Brouwer hertogJan = new Brouwer { BrouwerNr = 2, Brouwernaam = "Hertog Jan", Belgisch = false };
hertogJan.Bieren = new List<Bier> {
new Bier{ BierNr=4, Biernaam="Hertog Jan Dubbel", Alcohol=7.0F, Brouwer=hertogJan},
new Bier{ BierNr=5, Biernaam="Hertog Jan Grand Prestige", Alcohol=10.0F, Brouwer=hertogJan} };
lijst.Add(hertogJan);
Brouwer inBev = new Brouwer { BrouwerNr = 3, Brouwernaam = "InBev", Belgisch = true };
inBev.Bieren = new List<Bier> {
new Bier { BierNr=6, Biernaam="Belle-vue kriek L.A", Alcohol=1.2F, Brouwer=inBev},
new Bier { BierNr=7, Biernaam="Belle-vue kriek", Alcohol=5.2F, Brouwer=inBev},
new Bier { BierNr=8, Biernaam="Leffe Radieuse", Alcohol=8.2F,Brouwer=inBev},
new Bier { BierNr=9, Biernaam="Leffe Triple", Alcohol=8.5F,Brouwer=inBev} };
lijst.Add(inBev);
//return new List<Brouwer> { palm, hertogJan, inBev };
return lijst;
}
}
static void Main(string[] args)
{
var brouwers = new Brouwers().GetBrouwers();
var belgischeBrouwerijenMet3Bieren =
from brouwer in brouwers
where brouwer.Belgisch && brouwer.Bieren.Count == 3
select brouwer;
foreach (var brouwer in belgischeBrouwerijenMet3Bieren)
Console.WriteLine(brouwer.Brouwernaam);
var bieren = from brouwer in brouwers
from bier in brouwer.Bieren
select bier;
string vorigeBrouwer = "";
foreach (var bier in bieren)
{
if (bier.Brouwer.ToString() != vorigeBrouwer)
{
Console.WriteLine(bier.Brouwer);
vorigeBrouwer = bier.Brouwer.ToString();
}
Console.WriteLine($"\t {bier.ToString()}");
}
Console.WriteLine(printtabel(belgischeBrouwerijenMet3Bieren));
Console.ReadLine();
}
public string printtabel(IEnumerable<Brouwer> response)
{
StringBuilder sb = new StringBuilder();
foreach (PropertyInfo prop in response.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
object value = prop.GetValue(response, new object[] { });
sb.AppendLine($"{prop.Name} = {value}");
}
return sb.ToString();
}
}
}
Error CS0120 An object reference is required for the non-static field, method, or property 'Program.printtabel(IEnumerable)' LINQ 204 Active
You can fix it by writing:
public static string printtabel(IEnumerable<Brouwer> response)
You are calling a non static method from a static method. Set printtabel static and this error should disappear.
Related
I am using dotConnect for MySQL product of Devart. MySQL database structure likes this:
I am getting data like this:
public int user_id { get; set; } = 2;
public string lang { get; set; } = "en"; // Depending on the situation, it may also be "tr".
private readonly mainDataContext _db = new();
var cats = _db.categories.Where(s => s.u_id == user_id);
foreach (var cat in cats)
{
MessageBox.Show(cat.name_en);
}
In the MessageBox.Show I can not use cat.name + "_" + lang like PHP. I don't know how to get over this problem.
In nutshell, you can use this:
cat.GetType().GetProperty("name_" + lang).GetValue(cat,null))
But it's better to call a method to get value:
static public T getval<T>(Object obj, string field)
{
return (T)obj.GetType().GetProperty(field).GetValue(obj, null);
}
Here is a full example:
using System;
namespace Example
{
public class user
{
public int user_id { get; set; } = 2;
public string name_en { get; set; }
public string name_tr { get; set; }
}
class Program
{
static public T getval<T>(Object obj, string field)
{
return (T)obj.GetType().GetProperty(field).GetValue(obj, null);
}
static void Main(string[] args)
{
List<user> u = new List<user>();
u.Add(new user { user_id = 1, name_en = "Foods", name_tr = "name_tr value 1" });
u.Add(new user { user_id = 2, name_en = "Pizza", name_tr = "name_tr value 2" });
u.Add(new user { user_id = 2, name_en = "Other", name_tr = "name_tr vale 3" });
var lang = "en";
var cats = u.Where(s => s.user_id == 2);
foreach (var cat in cats)
{
Console.WriteLine(getval<string>(cat,"name_"+lang));
}
return;
}
}
}
I have to parse a TSV file which has the following structure:
[Secti
"1 2"
"2 3"his?
I'm not sure if this is what you were trying to do or not. I also noticed that it appeared to be 4 spaces between records. If it is actually a tab, you can change the delimiter to a tab Delimiter = "\t",
void Main()
{
var data = #"[Section one of info]
""Atr1 1""
""Atr2 2""
[Section two of info]
""Atr3 Atr4""
""1 2""
""2 3""
""4 5""";
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = " ",
Mode = CsvMode.Escape
};
using (var reader = new StringReader(data))
using (var csv = new CsvReader(reader, config))
{
var isSectionOne = true;
var record = new Foo() { Atr3 = new List<int>(), Atr4 = new List<int>() };
while(csv.Read())
{
if (csv.GetField(0).StartsWith("["))
continue;
if (isSectionOne)
{
if (csv.GetField(0) == "Atr1")
{
record.Atr1 = csv.GetField<int>(1);
}
if (csv.GetField(0) == "Atr2")
{
record.Atr2 = csv.GetField<int>(1);
}
if (csv.GetField(0) == "Atr3")
{
isSectionOne = false;
}
}
else
{
record.Atr3.Add(csv.GetField<int>(0));
record.Atr4.Add(csv.GetField<int>(1));
}
}
record.Dump();
}
}
public class Foo
{
public int Atr1 { get; set; }
public int Atr2 { get; set; }
public List<int> Atr3 { get; set; }
public List<int> Atr4 { get; set; }
}
I am trying to create an json data similar to this https://cdn.jsdelivr.net/gh/highcharts/highcharts#v7.0.0/samples/data/world-mortality.json
The current output I am getting is like this. The model name is being displayed and child does not seems to work. is t possible to remove the model field name on the serialize?
[{Name:"ABC",
Firstchild:[{Name:"AIR IMPORT",
Secondchild:[{NAME:"SCMBOA00052997",VALUE:69.7500},
{NAME:"SH123",VALUE:-100.0000},
{NAME:"SH456",VALUE:50.0000},
{NAME:"SH789",VALUE:150.0000}]
}]
}{Name:"DEF",
Firstchild:[{Name:"AIR IMPORT",
Secondchild:[{NAME:"SCMBOA00052997",VALUE:69.7500},
{NAME:"SH111",VALUE:-10.0000},
{NAME:"SH222",VALUE:80.0000},
{NAME:"SH333",VALUE:160.0000}]
}]
}]
What I need is like this
{
"ABC": {
"AIR IMPORT":{
"SH123": -100.0000,
"SH456": 50.0000,
"SH789": 150.0000
}
},
"DEF": {
"AIR IMPORT":{
"SH111": -10.0000,
"SH222": 80.0000,
"SH333": 160.0000
}
}
}
MODEL
public class ParentTreemap
{
public string Name { get; set; }
public List<FirstChildTreemap> Firstchild { get; set; }
}
public class FirstChildTreemap
{
public string Name { get; set; }
public List<SecondChildTreemap> Secondchild { get; set; }
}
public class SecondChildTreemap
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public decimal Value { get; set; }
}
Controller
var parent = treemaplist.Where(s => s.Parent == 0);
List<ParentTreemap> plist = new List<ParentTreemap>();
foreach (var item in parent)
{
var firstchild = treemaplist.Where(s => s.Parent == item.Id && s.Value==0);
List<FirstChildTreemap> flist = new List<FirstChildTreemap>();
foreach (var fitem in firstchild)
{
var secondchild = treemaplist.Where(s => s.Parent == fitem.Id && s.Value!=0);
List<SecondChildTreemap> slist = new List<SecondChildTreemap>();
foreach (var sitem in secondchild)
{
SecondChildTreemap model = new SecondChildTreemap();
model.Name = sitem.Name;
model.Value = sitem.Value;
slist.Add(model);
}
FirstChildTreemap child = new FirstChildTreemap();
child.Name = fitem.Name;
child.Secondchild = slist;
flist.Add(child);
}
ParentTreemap pmodel = new ParentTreemap();
pmodel.Name = item.Name;
pmodel.Firstchild = flist;
plist.Add(pmodel);
}
var stringWriter = new StringWriter();
var serializer = new JsonSerializer();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, plist);
}
ViewData["result"] = stringWriter;
namespace Calendar
{
public partial class MainCalendar : Form
{
private JArray items;
private List<String> AMList = new List<String>();
private List<String> PMList = new List<String>();
private List<String> accessToCalendarFilepath = new List<String>();
private List<CalendarModel> people;
private List<List<CalendarModel>> managers = new List<List<CalendarModel>>();
private List<String> userSelection = new List<String>();
private bool authorizedAccess = false;
private String javaScriptFileContainingJSONObject = "";
public MainCalendar()
{
InitializeComponent();
var locationInformation = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar + "location.json";
using (StreamReader file = File.OpenText(locationInformation))
using (JsonTextReader reader = new JsonTextReader(file))
{
JArray o = (JArray)JToken.ReadFrom(reader);
items = o;
}
foreach (var item in items.Children())
{
var itemProperties = item.Children<JProperty>();
// you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "name");
var myElementValue = myElement.Value; ////This is a JValue type
if(myElementValue.ToString().Contains("AM"))
{
AMList.Add(myElementValue.ToString());
}
if (myElementValue.ToString().Contains("PM"))
{
PMList.Add(myElementValue.ToString());
}
}
mondayAM.DataSource = AMList.ToArray();
tuesdayAM.DataSource = AMList.ToArray();
wednesdayAM.DataSource = AMList.ToArray();
thursdayAM.DataSource = AMList.ToArray();
fridayAM.DataSource = AMList.ToArray();
mondayPM.DataSource = PMList.ToArray();
tuesdayPM.DataSource = PMList.ToArray();
wednesdayPM.DataSource = PMList.ToArray();
thursdayPM.DataSource = PMList.ToArray();
fridayPM.DataSource = PMList.ToArray();
loadAccessControl("accesscontrol.json");
dateTimePicker1.AlwaysChooseMonday(dateTimePicker1.Value);
String dateSelected = dateTimePicker1.Value.ToShortDateString();
findManagerForSelectedDate(dateSelected);
}
public void loadAccessControl(String fileName)
{
var accessControlInformation = Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName;
List<AccessControl> accounts = JsonConvert.DeserializeObject<List<AccessControl>>(File.ReadAllText(accessControlInformation));
foreach (AccessControl account in accounts)
{
Console.WriteLine(account.accountName);
if (account.accountName.ToLower().Contains(Environment.UserName.ToLower()))
{
foreach (CalendarFile file in account.files)
{
// Console.WriteLine(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
accessToCalendarFilepath.Add(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
}
break;
}
}
contentsOfFile();
}
private void contentsOfFile()
{
String line;
foreach(var file in accessToCalendarFilepath)
{
StreamReader contentsOfJSONFile = new StreamReader(file);
while((line = contentsOfJSONFile.ReadLine()) != null)
{
if(line.Contains("var "))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "[";
}
else if(line.Contains("];"))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "]";
}
else
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + line;
}
}
people = JsonConvert.DeserializeObject<List<CalendarModel>>((string)javaScriptFileContainingJSONObject);
managers.Add(people);
javaScriptFileContainingJSONObject = "";
}
}
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name); // CRASHING HERE
//{"Exception of type 'System.OutOfMemoryException' was thrown."}
}
}
}
else
{
userSelection.Add(c.name);
}
}
}
Console.WriteLine();
}
I keep running out of memory.
The CalendarModel class:
namespace Calendar
{
class CalendarModel
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date")]
public string date { get; set; }
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("mondayAM")]
public string mondayAM { get; set; }
[JsonProperty("mondayPM")]
public string mondayPM { get; set; }
[JsonProperty("tuesdayAM")]
public string tuesdayAM { get; set; }
[JsonProperty("tuesdayPM")]
public string tuesdayPM { get; set; }
[JsonProperty("wednesdayAM")]
public string wednesdayAM { get; set; }
[JsonProperty("wednesdayPM")]
public string wednesdayPM { get; set; }
[JsonProperty("thursdayAM")]
public string thursdayAM { get; set; }
[JsonProperty("thursdayPM")]
public string thursdayPM { get; set; }
[JsonProperty("fridayAM")]
public string fridayAM { get; set; }
[JsonProperty("fridayPM")]
public string fridayPM { get; set; }
[JsonProperty("saturdayAM")]
public string saturdayAM { get; set; }
[JsonProperty("saturdayPM")]
public string saturdayPM { get; set; }
}
}
I keep crashing at
userSelection.Add(c.name)
Take a close look at what you are doing
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name);
}
}
You are adding to userSelection in the userSelection loop
The test is on !addedUser.Contains
You should not even be able to do that but I think the ToArrray() is letting it happen
So you add Sally
Then then Mark
Then you add Mark again because in the loop Mark != Sally
You are not using List<String> managerNames = new List<String>();
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
You pass in dateSelected, then overright with dateTimePicker1, and then you don't even use it
Most of you code makes very little sense to me
I have class object like this:
public class SD
{
public string s { get; set; }
}
public class Obj
{
public string p { get; set; }
public string u { get; set; }
public List<SD> sD { get; set; }
}
public class ObjAssignStudy
{
public List<Obj> obj { get; set; }
}
And I get that data in this way:
{
"obj":[
{"p":"1","usertype":"A","studyData":[{"study":"1"},{"study":"2"}]},
{"p":"2","usertype":"A","studyData":[{"study":"1"}]}
{"p":"1","usertype":"A","studyData":[{"study":"2"},{"study":"3"}]}
]
}
What i want is, I want to get distinct P and append coresponding s to it ie. I want final object to contain data like this:
{
"obj":[
{"p":"1","usertype":"A","studyData":[{"study":"1"},{"study":"2"},{"study":"3"}]},
{"p":"2","usertype":"A","studyData":[{"study":"1"}]}
]
}
Any way by which I can achieve this in c# or linq?
var objs = new List<Obj>(){
new Obj
{
p = "1",
u = "A",
sD = new List<SD>() {new SD() { s = "1"}, new SD() { s = "2"}}
},
new Obj
{
p = "2",
u = "A",
sD = new List<SD>() {new SD() { s = "1"}}
},
new Obj
{
p = "1",
u = "A",
sD = new List<SD>() {new SD() { s = "2"}, new SD() { s = "3"}}
}
};
var distinct = from obj in objs
group obj by new { obj.p } into g
select new Obj {
p = g.Key.p,
u = g.First().u,
sD = g.SelectMany(i => i.sD).Distinct().ToList()
};
Modify class SD to use Distinct
public class SD
{
public string s { get; set; }
public override bool Equals(object obj)
{
return string.Equals(s, (obj as SD).s);
}
public override int GetHashCode()
{
return s.GetHashCode();
}
}
In this particular scenario you can use indexer to take particular List<SD> corresponding to the value you are passing to the object please go through the code that will explain it in detail;
Creation of Indexer
public List<SD> this[string index]
{
get
{
foreach (Obj item in ListObj)
{
if (item.p == index)
return item.sD;
}
return new List<SD>();
}
}
In the main function you can access the indexer and store Collect the details as the follows:
static void Main(string[] args)
{
ObjAssignStudy newInstance = new ObjAssignStudy();
List<SD> sampleData=newInstance["b"];// Gives the output
//collection as : EmptyList1,EmptyList2
}
Complete Code for your reference is here:
class Program
{
static void Main(string[] args)
{
ObjAssignStudy newInstance = new ObjAssignStudy();
List<SD> sampleData=newInstance["c"];
}
public class SD
{
public string s { get; set; }
}
public class Obj
{
public string p { get; set; }
public string u { get; set; }
public List<SD> sD { get; set; }
}
public class ObjAssignStudy
{
private List<Obj> _ListObj= new List<Obj>();
internal List<Obj> ListObj
{
get { return _ListObj; }
set { _ListObj = value; }
}
List<SD> tempList = new List<SD>();
public ObjAssignStudy()
{
tempList.Add(new SD() { s = "EmptyList1" });
ListObj.Add(new Obj() { p = "a", sD = tempList, u = "B" });
tempList.Add(new SD() { s = "EmptyList2" });
ListObj.Add(new Obj() { p = "b", sD =tempList, u = "C" });
tempList.Add(new SD() { s = "EmptyList3" });
ListObj.Add(new Obj() { p = "c", sD =tempList, u = "D" });
}
public List<SD> this[string index]
{
get
{
foreach (Obj item in ListObj)
{
if (item.p == index)
return item.sD;
}
return new List<SD>();
}
}
}
}
Test Cases:
List sampleData=newInstance["a"];// Gives the output
EmptyList1
List<SD> sampleData=newInstance["a"];// Gives the output
EmptyList1
EmptyList2
List<SD> sampleData=newInstance["a"];// Gives the output
EmptyList1
EmptyList2
EmptyList3