First I would like to say sorry that I didn't use english but you will have the general idea of what I am trying to do.
Create class subjects variables and characteristics / properties:
- kodiILendes
- emriILendes
- nota
The method Main should make it possible for users to introduce these data, code
file, the file name and grade.
You need to create objects for 5 subjects
Make use of accessories (get and set), to mark So while you should assign grades should not be
less than 5 and also must not be greater than 10.
And to submit your average for this semester format, p.sh .: "Your Average
It is 9.3 ".
class Lendet
{
public int kodiIlendes;
public string emriIlendes;
private int nota;
public int Nota {
get {
return nota;
}
set {
if (value > 5 && value <= 10)
{
nota = value;
}
else {
Console.WriteLine("Nota duhet te jet me e > se 5 dhe nuk duhet te jet me e > se 10 ");
}
}
}
}
static void Main(string[] args)
{
Lendet Anglisht = new Lendet();
Anglisht.kodiIlendes = 100;
Anglisht.emriIlendes = "Anglisht";
Anglisht.Nota = 10;
}
Now lets imagine I created the 5 objects and I want to find the average.How can I do that ?
One way is like this Console.WriteLine(x.Nota+y.Nota+z.Nota+b.Nota+c.Nota/5)
class Lendet
{
public int kodiIlendes;
public string emriIlendes;
public static float sum;
public static int count;
public Lendet()
{
count++;
}
private int nota;
public int Nota {
get {
return nota;
}
set {
if (value > 5 && value <= 10)
{
sum =sum+value;
nota = value;
}
else {
Console.WriteLine("Nota duhet te jet me e > se 5 dhe nuk duhet te jet me e > se 10 ");
}
}
}
}
static void Main(string[] args)
{
//create object1
// create object2
//......create object n
Console.WriteLine(Lendet.sum/Lendet.count);
}
create two static variables, one for count of objects created and other for sum. Divide second by first to get the average.
My approach, with history:
class Lendet
{
public int Nota { get; private set; }
public Lendet(int nota)
{
this.Nota = nota;
LendetHistory.Add(this);
}
}
static class LendetHistory
{
private static List<Lendet> lendets = new List<Lendet>();
public static float Average()
{
if(lendets.Count < 1)
return 0;
return lendets.Select(s => s.Nota).Average();
}
public static void Add(Lendet lendet)
{
lendets.Add(lendet);
}
}
use in code:
var k = new Lendet(10);
var c = new Lendet(20);
Console.WriteLine(LendetHistory.Average());
and with that approach you can expand your logic
Related
I want to make an application where I can type a word and then a number. After typing all I want I want an output of them sorted alphabetical. The problem is that the words sort but the numbers don't sort with them because they are 2 different lists. How can i merge this 2 lists? I don't want to add them together like AddRange I need the out put like Console.WriteLine ("x{0}+" "+"{1}", numbers, words.
I've tried words.Sort(); but it just sorted the words and not both. So how can I merge the 2 lists?
The question is probably clear but in case you need some code there it is:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace zutaten
{
namespace mengen
{
class Program
{
static int hello;
static List<string> zutaten = new List<string>();
static List<int> mengen = new List<int>();
public static int memo;
public static int d = 1;
static List<string> zusammen = new List<string>();
static public bool Main(string[] args)
{
bool fertig = false;
while (!fertig)
{
var wert = Console.ReadLine();
if (wert != "f")
{
if (Gleich(zutaten, mengen))//zutaten.Count == mengen.Count)
{
if (KeineZutaten(wert))//int.TryParse(wert, out int keineZutat))
{
KeineZutatenAussage(wert);
}
else
{
if (Beinhaltet(wert)) //zutaten.Contains(wert)
{
Removen(wert);
// int index = zutaten.IndexOf(wert);
// zutaten.RemoveAt(index);
// mengen.RemoveAt(index);
}
//-------
Zutathinzufügen(wert);
//zutaten.Add(wert);
}
}
else
{
if (ParseMenge(wert, out memo))//int.TryParse(wert, out int menge))
{
Mengehinzufügen(memo);// mengen.Add(menge);
}
else
{
Mengepluseins(mengen);
//mengen.Add(1);
//--------
if (Beinhaltet(wert))
{
Removen(wert);
// int index = zutaten.IndexOf(wert);
// zutaten.RemoveAt(index);
// mengen.RemoveAt(index);
}
//------
Zutathinzufügen(wert);
//zutaten.Add(wert);
}
}
}
else
{
fertig = Fertigt();
if (!Gleich(zutaten, mengen))
{
Mengepluseins(mengen);
}
Forschleife(zutaten);
//for (int i = 0; i < zutaten.Count; i++)
//{
// Console.WriteLine("x{0} {1}", mengen[i], zutaten[i]);
//}
}
}
}
public static string MeineMethode()
{
return "string";
}
public static bool Gleich(List<string> variable1, List<int> variable2)
{
return variable1.Count == variable2.Count;
}
public static bool KeineZutaten(string wert1)
{
return int.TryParse(wert1, out hello);
}
public static void KeineZutatenAussage(string wert2)
{
Console.WriteLine("{0} ist keine Zutat", wert2);
}
public static bool Beinhaltet(string hulu)
{
return zutaten.Contains(hulu);
}
public static void Removen(string wertt)
{
int index = zutaten.IndexOf(wertt);
zutaten.RemoveAt(index);
mengen.RemoveAt(index);
}
public static void Zutathinzufügen(string werttt)
{
zutaten.Add(werttt);
}
// int index = zutaten.IndexOf(wert);
// zutaten.RemoveAt(index);
// mengen.RemoveAt(index);
//int.TryParse(wert, out int keineZutat
//zutaten.Add(wert);
public static bool ParseMenge(string wert1, out int var2)
{
return int.TryParse(wert1, out var2);
}
//int.TryParse(wert, out int menge))
public static void Mengehinzufügen(int var1)
{
mengen.Add(var1);
}
// mengen.Add(menge);
public static void Mengepluseins(List<int> mengen)
{
mengen.Add(d);
}
//mengen.Add(1);
public static bool Fertigt()
{
return true;
}
//fertig = true;
public static bool Mengeungleichzutaten(List<string> variable1, List<int> variable2)
{
return variable1.Count != variable2.Count;
}
//if (mengen.Count != zutaten.Count)
//{
// mengen.Add(1);
//}
public static void Forschleife(List<string> hey)
{
zutaten.Sort();
for (int i = 0; i < hey.Count; i++)
{
Console.WriteLine("x{0}"+" "+"{1}, mengen[i], zutaten[i]);
}
}
Input example :
Pork[Enter]
3[Enter]
Tomatoes[Enter]
6[Enter]
Potatoes[Enter]
2[Enter]
Expected output :
3x Pork
2x Potatoes
6x Tomatoes
Current output :
3x Pork
6x Potatoes
2x Tomatoes
Assuming these can be arrays, then you can use the native sort command to sort the two arrays according to one of them. This example sorts by the scores:
static void Main(string[] args)
{
int[] classScores = new int[]{30,50,25,39,62};
string[] studentNames = new string[]{"Jim","John","Mary","Peter","Sarah"};
Array.Sort(classScores, studentNames); // sort both according to scores
for (int i = 0; i < classScores.Length; i++)
{
Console.WriteLine(classScores[i] + " " + studentNames[i]);
}
}
You can use a SortedDictionary to store your values. The key being the product name, the value its quantity. This will be automatically sorted by key.
static SortedDictionary<string, int> GetProducts()
{
// Type of the
// key
// | Type of the
// | value
// | |
// v v
var Products = new SortedDictionary<string, int>();
while (true)
{
var product = "";
int quantity;
// First, ask the user to enter a product. If he enters nothing, ask again
while (product == "")
{
Console.WriteLine("Please enter a product name or f to finish");
product = Console.ReadLine();
if (product == "f")
return Products; // we are done, we can return the SortedDictionary
}
// Now, get the quantity
do
{
Console.WriteLine($"Please enter a quantity for {product}");
// Ask again if the user enters an invalid number
} while (!Int32.TryParse(Console.ReadLine(), out quantity));
// Store the informations in the SortedDictionary
Products[product] = quantity;
}
}
public static void Main()
{
// Get the products
var Products = GetProducts();
// Display them
foreach (var key in Products.Keys)
Console.WriteLine($"{Products[key]}x {key}");
}
Input :
Please enter a product name or f to finish
Pork
Please enter a quantity for Pork
3
Please enter a product name or f to finish
Tomatoes
Please enter a quantity for Tomatoes
6
Please enter a product name or f to finish
Potatoes
Please enter a quantity for Potatoes
2
Please enter a product name or f to finish
f
Output :
3x Pork
2x Potatoes
6x Tomatoes
In this program, I have 2 classes Application and Customer. I want to initialize Standard Fare with some value which should be entered by the user. Standard Fare field is in Customer class.
I did this, but it is not showing the desired result. When Calculate function is called The Value of Standard fare is becoming zero.
When I initialize the value of STANDARD_FARE in Customer class itself, then the program is working as desired.
How can I input the value given by the user to STANDARD_FARE?
Also methods like GetAge(), GetPassNo() in Application class is not returning the value of the same.
class Application
{
private static int Nop ;
private static double TotalFare=0;
Customer cust= new Customer();
static void Main(string[] args)
{
Application obj = new Application();
Console.Write("Enter the STANDARD RATE of the tour ");
obj.cust.StandardFare = int.Parse(Console.ReadLine());
a:
Console.Clear();
Console.WriteLine("Enter the number of passengers");
Nop = int.Parse(Console.ReadLine());
Application[] app = new Application[Nop];
if (Nop <= 0)
{
Console.WriteLine("Please enter a valid number of passengers");
Console.ReadKey();
goto a;
}
for (int i = 0; i < Nop; i++)
{
app[i] = new Application();
app[i].GetInformationFromCust();
}
for (int j = 0; j < Nop; j++)
{
app[j].cust.Display();
}
}
public int GetInformationFromCust()
{
b:
Console.Clear();
int slen = 0;
Console.WriteLine("Enter the title of the passenger");
cust.Customer_Title = Console.ReadLine();
Console.WriteLine("\r\nEnter passenger's First name :");
cust.Customer_FName = Console.ReadLine();
Console.WriteLine("\r\nEnter passenger's Last name :");
cust.Customer_LName = Console.ReadLine();
slen = cust.Customer_FName.Length + cust.Customer_LName.Length;
if (slen < 5 || slen > 15)
{
Console.WriteLine("\r\nName should be between 5 to 15 characters, Please try again ");
Console.ReadLine();
goto b;
}
c:
long x = 0, len = 0;
Console.WriteLine("\r\nEnter the passport number of the passenger ");
cust.CustomerPassNo = int.Parse(Console.ReadLine());
x = cust.CustomerPassNo;
while (x > 0)
{
x = x / 10;
++len;
}
if (len != 8)
{
Console.WriteLine("\r\nInvalid passport number, passport should be of 8 digits ");
goto c;
}
d:
Console.WriteLine("\r\nEnter the age of the passenger :");
cust.Customer_Age = int.Parse(Console.ReadLine());
if (cust.Customer_Age < 0)
{
Console.WriteLine("\r\nInvalid age, please enter a valid age ");
goto d;
}
cust.CalculatePrice();
return 0;
}
public int GetAge()
{
return cust.Customer_Age;
}
public double GetAirFare()
{
return cust.CustomerTicket ;
}
public long GetPassportNo()
{
return cust.CustomerPassNo;
}
public string GetTitle()
{
return cust.Customer_Title;
}
}
class Customer
{
const double K_DISCOUNT = 0.10;
const double S_DISCOUNT = 0.20;
private double STANDARD_FARE;
private string CustomerName { get; set; }
private int CustomerAge;
private string CustomerFName;
private string CustomerLName;
private long CustomerPassport;
private double CustomerPrice;
private string CustomerTitle;
private double KidDiscount;
private double SeniorDiscount;
public Customer()
{
this.KidDiscount = K_DISCOUNT;
this.SeniorDiscount = S_DISCOUNT;
}
public double StandardFare
{
get { return STANDARD_FARE; }
set { STANDARD_FARE = value; }
}
public int Customer_Age
{
get { return CustomerAge; }
set { CustomerAge = value; }
}
public string Customer_Title
{
get { return CustomerTitle; }
set { CustomerTitle = value; }
}
public string Customer_FName
{
get { return CustomerFName; }
set { CustomerFName = value; }
}
public string Customer_LName
{
get { return CustomerLName; }
set { CustomerLName = value; }
}
public long CustomerPassNo
{
get { return CustomerPassport; }
set { CustomerPassport = value; }
}
public double CustomerTicket
{
get { return CustomerPrice; }
set { CustomerPrice = value; }
}
public int CalculatePrice()
{
if (CustomerAge < 3)
{
CustomerPrice = 0;
}
else if (CustomerAge >= 3 && CustomerAge < 18)
{
CustomerPrice = STANDARD_FARE - (STANDARD_FARE * KidDiscount);
}
else if (CustomerAge > 65)
{
CustomerPrice = STANDARD_FARE - (STANDARD_FARE * SeniorDiscount);
}
else
{
CustomerPrice = STANDARD_FARE;
}
return 0;
}
public void Display()
{
//some code here
}
}
You are populating your array app with instances of Application that still have the default STANDARD_FARE value (which is 0.0), because you have never set it on those instances. You only set it on the obj.cust instance, which you never again use. Because STANDARD_FARE is an instance variable, changes to it have no affect on other (or future) instances.
You have the same problem in reverse with all the Application.Get* functions; they are getting properties of an object (obj.cust) that has never had any properties set, other than StandardFare/STANDARD_FARE.
The most obvious fix is to do away with obj and obj.cust entirely - they have no use other than to be confusing - and make STANDARD_FARE a static variable (and its setter StandardFare a static property).
BTW, your naming conventions are terrible and inconsistent; if I were your grader I'd dock you points for using unclear variable names(app, nop), and for using ALL_CAPS for non-constants (STANDARD_FARE). I'd also object to using a private auto-backed property (CustomerName, which is also never used) instead of simply a private variable, for not using auto-backed properties elsewhere (StandardFare as an explicitly-coded public getter and setter for STANDARD_FARE, etc.), and for copying constant values into non-settable instance variables (K_DISCOUNT to KidDiscount; just use the constant directly, or at least make KidDiscount static and add some non-private access to it). As others have mentioned, you of course should not be using goto in place of loops. I'll also mention the error-prone and inefficient checking the length of the passport number by repeated division instead of simply checking whether it's less than 99999999 (in theory, passport numbers might start with a zero, which would look like less than 8 digits after parsing, but you could also make sure it's greater than 10000000 if you want).
Having a model something like this (I cannot change this):
public class SomeObject
{
public int Amount { get; set; }
public int TotalAmount { get; set; }
}
I need to iterate an array of SomeObject to populate some values and accumulate (perform not simple calculations) another fields.
static void Main(string[] args)
{
List<SomeObject> myCollection = new List<SomeObject>()
{
new SomeObject() { Amount = 3 },
new SomeObject() { Amount = 6 },
new SomeObject() { Amount = 9 }
};
int totalAccumulated = 0;
for (int i = 0; i < myCollection.Count; i++)
{
PopulateAndCalculate(myCollection[i], ref totalAccumulated);
}
//I don't want to create here a second for to iterate again all myCollection to set his TotalAmount property.
//There is another way?
Console.WriteLine($"The total accumulated is: {totalAccumulated}");
}
private static void PopulateAndCalculate(SomeObject prmObject, ref int accumulatedTotal)
{
//Populate a lot of another fields
accumulatedTotal += prmObject.Amount;
prmObject.TotalAmount = accumulatedTotal; //This don't work, but I need something alike
}
I don't want a second for statement to update TotalAmount property of each item in myCollection.
The main requirement is iterate the whole array, few times, don't care about string interpolation this is a short demo, this code must run in .net 2.0.
Theres is a clean/better way?
The solution is actually simple, though it's not exactly a good coding practice.
What you really need is for TotalAmount to be a static property. Without that, there's this:
static void Main(string[] args)
{
List<SomeObject> myCollection = new List<SomeObject>()
{
new SomeObject() { Amount = 3 },
new SomeObject() { Amount = 6 },
new SomeObject() { Amount = 9 }
};
int totalAccumulated = 0;
for (int i = 0; i < myCollection.Count; i++)
{
PopulateAndCalculate(myCollection[i], ref totalAccumulated);
}
/*****This is the new part*******/
myCollection[0].TotalAmount = totalAccumulated;
myCollection[1].TotalAmount = totalAccumulated;
myCollection[2].TotalAmount = totalAccumulated;
Console.WriteLine($"The total accumulated is: {totalAccumulated}");
}
private static void PopulateAndCalculate(SomeObject prmObject, ref int accumulatedTotal)
{
//Populate a lot of another fields
accumulatedTotal += prmObject.Amount;
//no need to mess with the total here as far as the properties are concerned.
}
You can st fields inside linq expression.
Could you consider this please
myCollection.ForEach(c => c.TotalAmount = myCollection.Sum(a => a.Amount));
Console.WriteLine($"Total accumulated :{myCollection.First().TotalAmount}");
I found a solution using the Observer Pattern.
Firstly I created a global delegate to be used by an event:
public delegate void UpdateTotalAmountDelegate(int totalAmount);
Then a new class called: 'CalculatorSetter'
public class CalculatorSetter
{
public event UpdateTotalAmountDelegate UpdateTotalAmounthHandler;
public void UpdateTotalAmount(int prmTotalAmount)
{
UpdateTotalAmounthHandler(prmTotalAmount);
}
}
I refactor the data object 'SomeObject' adding a field of type CalculatorSetter.
public class SomeObject
{
private CalculatorSetter finalCalculator;
public void SetCalculator(CalculatorSetter prmCalculator)
{
this.finalCalculator = prmCalculator;
finalCalculator.UpdateTotalAmounthHandler += FinalCalculator_UpdateTotalAmounthHandler;
}
private void FinalCalculator_UpdateTotalAmounthHandler(int totalAmount)
{
this.TotalAmount = totalAmount;
}
//Some Other Fields
public int Amount { get; set; }
public int TotalAmount { get; set; }
}
And my original code and unique for:
static void Main(string[] args)
{
List<SomeObject> myCollection = new List<SomeObject>()
{
new SomeObject() { Amount = 3 },
new SomeObject() { Amount = 6 },
new SomeObject() { Amount = 9 }
};
CalculatorSetter commonCalculator = new CalculatorSetter();
int totalToAccumulate = 0;
for (int i = 0; i < myCollection.Count; i++)
{
PopulateAndCalculate(myCollection[i], commonCalculator, ref totalToAccumulate);
}
commonCalculator.UpdateTotalAmount(totalToAccumulate);
Console.WriteLine($"The total accumulated is: {totalToAccumulate}");
Console.WriteLine($"The first total accumulated is: {myCollection[0].TotalAmount}");
}
Many thanks.
Use a wrapper and keep it simple (if you want you can change a little for use static methods you can, or static class but I dont see the point)
the result is:
The Amount is 3, The total ammount is 18
The Amount is 6, The total ammount is 18
The Amount is 9, The total ammount is 18
namespace Prueba1
{
class Program
{
public class WrapperInt {
public int Value { get; set; }
}
public class SomeObject
{
public int Amount { get; set; }
public WrapperInt TotalAmount { get; set; }
}
public Program() {
WrapperInt TotalAmountAllArrays = new WrapperInt();
List<SomeObject> myCollection = new List<SomeObject>()
{
new SomeObject() { Amount = 3, TotalAmount =TotalAmountAllArrays },
new SomeObject() { Amount = 6 , TotalAmount =TotalAmountAllArrays },
new SomeObject() { Amount = 9 , TotalAmount =TotalAmountAllArrays }
};
for (int i = 0; i < myCollection.Count; i++)
{
myCollection[i].TotalAmount.Value += myCollection[i].Amount;
}
foreach (var c in myCollection)
{
Console.WriteLine($"The Amount is:" + c.Amount + " The total ammount is:" + c.TotalAmount.Value);
}
}
static void Main(string[] args)
{
new Program();
}
}
}
Hopefully this will work for you… One possible solution is to create a wrapper class called MyTotalList which contains a List named amounts and an int named total. MyTotalList class does not expose its list amounts as an editable list. If the class exposes this list as editable, then other methods could ultimately change an items value in that list and the MyTotalList class would not be aware of this and unfortunately contain an incorrect total. To avoid this situation and for the class to work as expected, methods must use the MyTotalList’s Add and Remove methods. To ensure this happens, the private List amounts in the MyTotalList class returns a read only list which ensures that changes to the list will not be made outside the MyTotalList class. Leaving the list exposed and editable will/could cause the class to contain an incorrect total.
My solution is to create a Class that wraps a List. MyTotalList class has a no argument constructor. Once a new instance of a MyTotalList object is created you can then use that instance to Add MyObject items to its list. Every time an item is added to the MyTotalList, list amounts the variable total gets updated with the added item’s amount. Example:
Create a new MyTotalList object:
MyTotalList listOfObjects = new MyTotalList();
Then add some MyObject instances to the listOfObjects
listOfObjects.Add(new MyObject(1,3));
listOfObjects.Add(new MyObject(2,6));
listOfObjects.Add(new MyObject(3,9));
After you add the items, you can then use the listOfObjects Total property to get the total sum of all MyObject items in the list with:
listOfObjects.Total
If you need to pass or use the List of MyTotalList items you can use:
listOfObjects.Items
Bear in mind as I discussed above, this List Items is a read-only list. Therefore you cannot add/remove items in this list as you would an editable list. So the code below will fail during implementation as these methods are not exposed for read only objects.
listOfObjects.Items.Remove(new MyObject(4, 10));
listOfObjects.Items.Add(new MyObject(4, 10));
The above lines will cause the compiler to complain: xxx… does not contain a definition for Add/Remove. This ensures methods will use the MyTotalList.Add and MyTotalsList.Remove methods and eliminate any possibility of the list changing outside the MyTotalList class.
MyObject Class
class MyObject : IComparable {
public int id { get; }
public int amount { get; }
public MyObject(int inID, int inAmount) {
id = inID;
amount = inAmount;
}
public override string ToString() {
return amount.ToString();
}
public override int GetHashCode() {
return id.GetHashCode();
}
public override bool Equals(object other) {
if (other != null)
return (this.id == ((MyObject)other).id);
return false;
}
public int CompareTo(object other) {
if (this.id > ((MyObject)other).id)
return 1;
if (this.id < ((MyObject)other).id)
return -1;
return 0;
}
}
MyTotalList Class
class MyTotalList {
private int total;
private List<MyObject> amounts;
public MyTotalList() {
total = 0;
amounts = new List<MyObject>();
}
public int ListCount {
get { return amounts.Count; }
}
public IReadOnlyCollection<MyObject> Items {
get { return amounts.AsReadOnly(); }
}
public int Total {
get { return total; }
}
public void Add(MyObject other) {
if (other != null) {
if (!(amounts.Contains(other))) {
total += other.amount;
amounts.Add(other);
}
else {
Console.WriteLine("Duplicate id's not allowed!");
}
}
}
public void Remove(MyObject other) {
if (amounts.Contains(other)) {
total -= amounts[amounts.IndexOf(other)].amount;
amounts.Remove(other);
}
else {
Console.WriteLine("Item to remove not found!");
}
}
}
Examples
MyTotalList listOfObjects = new MyTotalList();
listOfObjects.Add(new MyObject(1,3));
listOfObjects.Add(new MyObject(2,6));
listOfObjects.Add(new MyObject(3,9));
Console.WriteLine("----------------------------------------");
Console.WriteLine("Initial list with total");
Console.WriteLine("items in list:");
foreach (MyObject mo in listOfObjects.Items)
Console.Write(mo.ToString() + " ");
Console.WriteLine();
Console.WriteLine("Total from list of " + listOfObjects.ListCount +
" items is: " + listOfObjects.Total);
Console.WriteLine("----------------------------------------");
Console.WriteLine("Add three more items");
listOfObjects.Add(new MyObject(4, 10));
listOfObjects.Add(new MyObject(5, 11));
listOfObjects.Add(new MyObject(6, 12));
Console.WriteLine("items in list:");
foreach (MyObject mo in listOfObjects.Items)
Console.Write(mo.ToString() + " ");
Console.WriteLine();
Console.WriteLine("Total from list of " + listOfObjects.ListCount +
" items is: " + listOfObjects.Total);
Console.WriteLine("----------------------------------------");
Console.WriteLine("Remove id 4 (10) from the list");
listOfObjects.Remove(new MyObject(4, 10));
Console.WriteLine("items in list:");
foreach (MyObject mo in listOfObjects.Items)
Console.Write(mo.ToString() + " ");
Console.WriteLine();
Console.WriteLine("Total from list of " + listOfObjects.ListCount +
" items is: " + listOfObjects.Total);
A Side note to your original post…About the class you can not change
SomeObject {
public int Amount { get; set; }
public int TotalAmount { get; set; }
}
Regardless of how you get the total for theint varable: TotaAmount… for each instance of SomeObject class to contain the same variable with the same amount and you want to ensure this is true for all existing SomeObject instances… is well a poor design. This creates redundant data and simply waste space and it makes no sense for each variable to contain this value as it has absolutely nothing to do with that SomeObject instance. This class design is counter intuitive of a good design. As #Tim Schmelter’s comment points out "a single object should not know anything about the total amount of other objects." This “redundant data” situation is something a programmer should try to avoid, not promote.
I want to add row number in object list.
here's the they i do it now but there must be better way
Profile for mapping
public class VendorEnquiryDM_TO_VM : Profile
{
public VendorEnquiryDM_TO_VM()
{
CreateMap<VENDORENQUIRY, VendorEnquiryVM>();
}
}
public class VendorEnquiryVM_TO_DM : Profile
{
public VendorEnquiryVM_TO_DM()
{
CreateMap<VENDOR_ENQUIRY, VendorEnquiryVM>().ReverseMap();
}
}
Register profile
cfg.AddProfile<VendorEnquiryDM_TO_VM>();
cfg.AddProfile<VendorEnquiryVM_TO_DM>();
This is how I add sno.
alldata = Mapper.Map<IEnumerable<Vendor_EnquiryVM>>(objDAO.getVendorEnquiry());
var _roles = alldata.Select((t, index) => new Vendor_EnquiryVM
{
sno = index + 1,
CONTACT_NO=t.CONTACT_NO,
DATE=t.DATE,
EMAIL=t.EMAIL,
id=t.id,
FIRST_NAME=t.FIRST_NAME,
wer=t.wer,
asdf=t.asdf
});
Due to just one serial no. I need to assign all properties and this is somewhat fraustrating to me for large model, please suggest me better way of doing this.
You can define a static Id and when you create the class, increment it by one
here how your class code should look like
public class Test
{
private static int mId = 0;
public Test()
{
mId = mId +1;
}
public int Id
{
get{ return mId;}
}
}
Here a demo
in order to use the same idea with collections like List, I applied some modifications and here what you can do
public class Test
{
private static int mIndex = 0; // this parameter will be incremented for each new Test
private int mId =0; // this parameter will hold the last incremented value
public Test()
{
mId = ++mIndex; // mIndex++ if you want to start with 0
}
public int Id
{
get{ return mId;}
}
}
Demo with lists
hope this will help you
I want to learn how to create an object hierarchy (like that of excel vba).
I have written some code and want to ask if this is the right way to go. Also, I want to know if creating this type of object structure will have any significant effect on performance. I will access the objects as for e.g. this way :
Hotel hotel = new Hotel();
int x = hotel.Rooms[1].Count; // just an example
int y = hotel.Rooms.Room.Count; // just an example
class Hotel
{
private int i;
public Hotel()
{
i = 10; // some prossessing to give the value of i. Lets say 10
}
public _Rooms Rooms
{
get { return new _Rooms(i); }
}
}
class _Rooms
{
private int _i;
public _Rooms(int i)
{
this._i = i;
}
public _Room this[int i]
{
get { return new _Room(_i); }
}
public _Room Room // _Room Property
{
get { return new _Room(this._i); }
}
}
class _Room
{
private int _i;
public _Room(int i)
{
// some prossessing to give the value of i. Lets say :
_i = i + 10;
}
public int Count
{
get { _i = 15; return _i; }
}
}
This is just a simple example of the model that I want to achieve.