Increment through property names in object - c#

I have the following object:
namespace BluetoothExample
{
public class Assay
{
public double Band_1 //Vis450
{
get;
set;
}
public double Band_2 //Vis500
{
get;
set;
}
public double Band_3 //Vis550
{
get;
set;
}
public double Band_4 //Vis570
{
get;
set;
}
}
}
I want to populate the 4 bands in my object. Which I currently do in the following way:
public Populate()
{
int _i = 0;
double[] nirData = new double[4];
MyDevice.Characteristic.ValueUpdated += (sender, e) =>
{
nirData[_i] = BitConverter.ToDouble(e.Characteristic.Value, 0);
_i++;
};
Assay assay = new Assay();
assay.Band_1 = nirData[0];
assay.Band_2 = nirData[1];
assay.Band_3 = nirData[2];
assay.Band_4 = nirData[3];
}
I was wondering if it was possible to do the entire thing inside the MyDevice.Characteristic.ValueUpdate method instead? My thought is that it should be possible to increment and populate the properties of my object like so:
string name = "assay.Band_" + _i;
name = BitConverter.ToDouble(e.Characteristic.Value, 0);
This is obviously wrong, but it sort of demonstrates my idea.

Just make your band an Array, or List:
public class Assay
{
public double[] Band
{
get;
set;
}
}
And then you can simply assign it like:
public Populate()
{
int _i = 0;
double[] nirData = new double[4];
MyDevice.Characteristic.ValueUpdated += (sender, e) =>
{
nirData[_i] = BitConverter.ToDouble(e.Characteristic.Value, 0);
_i++;
};
Assay assay = new Assay();
assay.Band = nirData;
}

Related

Automapper: same instance after mapping

I try Automapper and it is very nice but is it possible map two OuterDto source to OuterModel destination with same object InnerDeto like in code? How can I do that dest1.Inner and dest2.Inner after map has same instance? What I know, I think it is not possible. What do you think? Thanks for help me
public class OuterDto
{
public int Value { get; set; }
public InnerDto Inner { get; set; }
}
public class InnerDto
{
public int OtherValue { get; set; }
}
public class OuterModel
{
public int Value { get; set; }
public InnerModel Inner { get; set; }
}
public class InnerModel
{
public int OtherValue { get; set; }
}
public class test
{
public test()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<InnerDto, InnerModel>().ReverseMap();
cfg.CreateMap<OuterDto, OuterModel>().ReverseMap();
});
config.AssertConfigurationIsValid();
InnerDto innerSource = new InnerDto { OtherValue = 15 };
var source1 = new OuterDto
{
Value = 1,
Inner = innerSource
};
var source2 = new OuterDto
{
Value = 2,
Inner = innerSource
};
var mapper = config.CreateMapper();
source1.Inner.OtherValue = 20;
var dest1 = mapper.Map<OuterDto, OuterModel>(source1);
var dest2 = mapper.Map<OuterDto, OuterModel>(source2);
dest1.Inner.OtherValue = 1000;
//Result:
//dest1.Inner.OtherValue = 1000
//dest2.Inner.OtherValue = 20
//Expected Result:
//dest1.Inner.OtherValue = 1000
//dest2.Inner.OtherValue = 1000
}
}
I'm not sure, but try to instanciate OuterModel before calling Map method
//...
var mapper = config.CreateMapper();
source1.Inner.OtherValue = 20;
var dest1 = new OuterModel();
mapper.Map(source1, dest1);
mapper.Map(source2, dest1);
dest1.Inner.OtherValue = 1000;
NOTE: I haven't tested my code, it's just to give food for thought

Databind chart with members from a field instance

I would like to put chart series in a List so that I can add new series dynamically. But I have not been able to figure out how to bind the data to the chart when it is structured like this. Maybe its not possible or there are better ways?
public class DataSerie {
public DataSerie(string _name, double _value) {
name = _name;
value = _value;
}
public string name { get; set; }
public double value { get; set; }
}
public class ChartData
{
public ChartData(double _x)
{
x = _x;
series = new List<DataSerie>();
}
public double x { get; set; }
public List<DataSerie> series { get; set; }
}
private List<ChartData> chartDataList = new List<ChartData>();
private void Form1_Load(object sender, EventArgs e)
{
ChartData cd;
cd = new ChartData(1);
cd.series.Add(new DataSerie("y1", 5));
cd.series.Add(new DataSerie("y2", 3));
cd.series.Add(new DataSerie("y3", 3));
chartDataList.Add(cd);
cd = new ChartData(2);
cd.series.Add(new DataSerie("y1", 5));
cd.series.Add(new DataSerie("y2", 4));
cd.series.Add(new DataSerie("y3", 2));
chartDataList.Add(cd);
chart1.DataSource = chartDataList;
chart1.Series.Clear();
ChartData c = chartDataList[0];
foreach (DataSerie serie in c.series) {
chart1.Series.Add(serie.name);
chart1.Series[serie.name].XValueMember = "X";
chart1.Series[serie.name].YValueMembers = "serie.value"; // This obviously doesnt work.
}
}
I solved it by iterating over the data and populate the chart like this: chart.Series[serie.name].Points.AddXY(data.x,data.y);
Instead of databinding

sql where clause rule in linq

I'm trying to put my SQL rule in Linq , as my rule get generated from query builder and I need to filter my data based on rule , this is my simple example
class Program
{
static void Main(string[] args)
{
PromotionVm lObjPromVm = new PromotionVm();
for (int i = 1; i <= 5; i++)
{
PromotionList lObjPromList = new PromotionList();
lObjPromList.active_indicator = 1;
lObjPromList.principle_code = "a" + i;
lObjPromList.promotion_code = "b" + i;
lObjPromList.promotion_plan_number = 20 + i;
lObjPromList.promotion_type_code = 30 + i;
lObjPromList.start_date = DateTime.Now.AddDays(i);
lObjPromVm.promotion_list.Add(lObjPromList);
}
//var sqlRule= "promotion_type_code = 'expensive' AND Category IN('Food', 'Transportation', 'Shopping') AND(PaymentMode = 'Cash' OR PaymentMode = 'Debit Card' OR(Amount = 35))";
var sqlRule = "promotion_type_code = '33'";
// lObjPromVm.promotion_list.ToDataTable()
var lOutlut = lObjPromVm.promotion_list.Where(sqlRule);
}
}
class PromotionVm
{
public List<PromotionList> promotion_list { get; set; }
public PromotionVm()
{
promotion_list = new List<PromotionList>();
}
}
public class PromotionList
{
public string principle_code { get; set; }
public string promotion_code { get; set; }
public int promotion_plan_number { get; set; }
public int promotion_type_code { get; set; }
public DateTime start_date { get; set; }
public int active_indicator { get; set; }
}
I'm trying to use System.Linq.Dynamic.Core; but not working.
Can anyone suggest how I can filter my data by SQL rules?
same question was asked here How to use a string in the linq where clause?
but response what is given , its not working .
I was able to solve the problem , I just needed to convert to AsQueryable() .
var sqlRule = "promotion_type_code in (31,33) or (promotion_code=\"b2\")";
var lOutlut = lObjPromVm.promotion_list.AsQueryable().Where(sqlRule);

I passed a value but it still return 0

I passed a value to a class and then from that class pass it to another class and get the value.
I tried to Parse the value, but it still didn't work, I also try to use getters and setters
public class Product
{
public string Title { get; set; }
public int Price { get; set; }
}
public class Book : Product
{
public string Isbn { get; set; }
public int Price2 { get; set; }
}
public class Check : Book
{
public int Num;
public int Num2;
public int Calculate(Book product) //This is important, I would like to keep practicing pass
{
Num = (product.Price);
Num2 = product.Price2;
Console.WriteLine(Num2);
return Num + Num2;
}
}
class Program
{
static void Main(string[] args)
{
var num = new Book();
var checkNum = num.Price = 10; //these is the values
var checkNum2 = num.Price2 = 20;
var result = new Check();
var checkNum3 = result.Calculate(new Book());
Console.WriteLine(checkNum3.Num);
}
}
I am expecting 30 as the result
Let's make what you have work
Calculate needs to get the book that has prices set.
Calculate returns the number, we don't need to use .Num.
var num = new Book();
var checkNum = num.Price = 10; //these is the values
var checkNum2 = num.Price2 = 20;
var result = new Check();
var checkNum3 = result.Calculate(num);
Console.WriteLine(checkNum3);
Better names
If you use better names it would be easier to follow.
var book = new Book();
book.Price = 10; //these is the values
book.Price2 = 20;
var check = new Check();
var calculated = result.Calculate(book);
Console.WriteLine(calculated);
Let's improve
A. (Best?) Check is a calulator
public class Check // Not a book
{
public static int Calculate(Book book)
{
var p = book.Price;
var p2 = book.Price2;
var total = p + p2;
Console.WriteLine(total);
return total;
}
}
(...)
var calculated = Check.Calculated(book); // no: new Check()
B. If Check has a Book.
The Check does not be a Book, it can have it.
public class Product
{
public string Title { get; set; }
public int Price { get; set; }
}
public class Book : Product
{
public string Isbn { get; set; }
public int Price2 { get; set; }
}
public class Check
{
private readonly Book book;
public Check(Book book)
{
this.book = book;
}
public int Calculate() => book.Price + book.Price2;
}
class Program
{
static void Main(string[] args)
{
var book = new Book();
book.Price = 10;
book.Price2 = 20;
var check = new Check(book);
Console.WriteLine(check .Calculate());
}
}
3 C. If Check is a Book
If Check is a Book it needs to store Price and Price2. Please consider the following example.
public class Product
{
public Product() { }
public Product(string title, int price)
{
Title = title;
Price = price;
}
public string Title { get; set; }
public int Price { get; set; }
}
public class Book : Product
{
public Book(Book book) : base(book.Title, book.Price)
{
Isbn = book.Isbn;
Price2 = book.Price2;
}
public Book() { }
public string Isbn { get; set; }
public int Price2 { get; set; }
}
public class Check : Book
{
public Check(Book book) : base(book)
{
// This should really call Book's contrcutor
}
public int Calculate() => Price + Price2;
}
class Program
{
static void Main(string[] args)
{
var b = new Book();
b.Price = 10;
b.Price2 = 20;
var c = new Check(b);
Console.WriteLine(c.Calculate());
}
}
To answer your immediate question, you're passing a new Book to the Calculate() method, and it has a value of zero for Price and Price2.
I believe what you're looking at is this:
var num = new Book();
num.Price = 10; //these is the values
num.Price2 = 20;
var result = new Check();
var checkNum3 = result.Calculate(num);
Note that I've removed checkNum and checkNum2 variables as they are redundant.
However, your code still has some problems.
It makes no sense to make Check a subclass of Book. It's usage seems to be sum the two prices, and for that it doesn't need to be a sub-class. It can stand on it's own. Furthermore, since it doesn't actually use the two prices for anything other than summing up the values, it doesn't even need to have the two int properties. It can be simplified as below:
public class Check
{
public int Calculate(Book product)
{
var sum = product.Price + product.Price2;
Console.WriteLine(sum);
return sum;
}
}
Finally, if you're only using the Check class to perform a calculation, it can actually be a static class so that you can call the method even without creating an instance of it.
public static class Check
{
public static int Calculate(Book product)
{
var sum = product.Price + product.Price2;
Console.WriteLine(sum);
return sum;
}
}
Now you can call it like so:
var num = new Book();
num.Price = 10;
num.Price2 = 20;
var checkNum3 = Check.Calculate(num);
public class Product
{
public string Title { get; set; }
public int Price { get; set; }
}
public class Book : Product
{
public string Isbn { get; set; }
public int Price2 { get; set; }
}
public class Check : Book
{
public int Calculate(Book product) //This is important, I would like to keep practicing pass
{
return product.Price+product.Price2
}
}
class Program
{
static void Main(string[] args)
{
var num = new Book();
num.Price = 10;
num.Price2 = 20;
var result = new Check();
Console.WriteLine(result.Calculate(num)); //pass num not new book
}
}

select child object collection with lambdas

I have the following class objects:
public class VacancyCategory
{
public int ID { get; set; }
public string Text { get; set; }
public IList<VacancySubCategory> SubCategories { get; set; }
}
public class VacancySubCategory
{
public int ID { get; set; }
public string Text { get; set; }
public VacancyCategory Category { get; set; }
public IList<Vacancy> Vacancies { get; set; }
}
public class Vacancy : IBusinessObject
{
public int ID { get; set; }
public string Title { get; set; }
public VacancySubCategory SubCategory { get; set; }
public string Body { get; set; }
public VacancyWorkType WorkType { get; set; }
public string Salary { get; set; }
public DateTime? AppsClosingDate { get; set; }
public bool Active { get; set; }
}
...so in a test repository im creating test data like so:
private IList<VacancyCategory> GetVacancyCategoriesWithAllChildCollections()
{
IList<VacancyCategory> vacancyCategories = new List<VacancyCategory>();
int cCounter = 0;
int scCounter = 0;
int vCounter = 0;
for (int i = 1; i <= 3; i++)
{
VacancyCategory vc = new VacancyCategory();
vc.ID = ++cCounter;
vc.Text = "VacancyCategory" + i.ToString();
for (int j = 1; j <= 3; j++)
{
VacancySubCategory vsc = new VacancySubCategory();
vsc.ID = ++scCounter;
vsc.Text = "VacancySubCategory" + scCounter.ToString();
vsc.Category = vc;
for (int k = 1; k <= 2; k++)
{
Vacancy v = new Vacancy();
v.ID = ++vCounter;
v.Title = "Vacancy" + vCounter.ToString();
v.Body = "VacancyBody" + vCounter.ToString();
v.Active = vCounter >= 16 ? false : true;
v.WorkType = this._workTypes.Single(wt => wt.ID == k);
v.Salary = vCounter <= 7 ? "SR " + (vCounter * 1000).ToString() : "";
v.AppsClosingDate = (vCounter >= 3 & vCounter <= 13) ? (new DateTime(2009, 3, vCounter)) : (DateTime?)null;
v.SubCategory = vsc;
if (vsc.Vacancies == null)
vsc.Vacancies = new List<Vacancy>();
vsc.Vacancies.Add(v);
}
if (vc.SubCategories == null)
vc.SubCategories = new List<VacancySubCategory>();
vc.SubCategories.Add(vsc);
}
vacancyCategories.Add(vc);
}
return vacancyCategories;
}
..so now i have some good test data. the object tree / chained objects are important to me.
so i'd like to return the individual object collections from this tree when desired. for example, if i wanted the whole tree, i can just return the VacancyCategory list with all the child objects - great. but now i want to return just the VacancySubCaregory items (all 9 of them). this would be my public method to the test repository:
public IQueryable<VacancySubCategory> GetVacancySubCategories()
{
throw new NotImplementedException("write gen code");
}
.. obviously without the exception. i have a member field called _categories that contains the results from the GetVacancyCategoriesWithAllChildCollections method. so i've been trying stuff like
this._categories.Select( ......
..but i cant seem to return a list of VacancySubCategory objects. i seem to always be selecting the root collection (ie. a result set of VacancyCategory objects). What am i doing wrong? im sure its simple... but its driving me nuts!
EDIT
thanx matt.
your suggestion led me to this:
public IQueryable<VacancySubCategory> GetVacancySubCategories()
{
return this._categories.SelectMany(c => c.SubCategories).AsQueryable<VacancySubCategory>();
}
..which works great. you're a champ
Try:
return this._categories.SelectMany(c => c.SubCategories);
This should work.
var query = from vc in GetVacancyCategoriesWithAllChildCollections()
from vcs in vc.SubCategories
select vcs

Categories