I have a class of houses (the channel enum is not displayed here)
The class has objects referenced and two constructors, and then inside the class there is a List called 'inventory' and two or more functions that try to access the list, What I'd like to do is use this same list across all of the separate functions inside of 'class houses'
but I am getting a 'does not exist in current context' error, Which makes me think this is a problem of scope.
But all the methods are in the same 'class houses' ... Aren't they of the same scope?
Obviously not following the right path, How should I look at this?
class property
{
public string AddressNumber { get; set; }
public string AddressStreet { get; set; }
public double ListingPrice { get; set; }
public double MonthlyRent { get; set; }
public double Taxes { get; set; }
public Channel Channel { get; set; }
public property(string addnum, string addstreet, double lp, double mr, double taxes, Channel rorm)
{
AddressNumber = addnum;
AddressStreet = addstreet;
ListingPrice = lp;
MonthlyRent = mr;
Taxes = taxes;
Channel = rorm;
}
public property()
{
AddressNumber = "4319";
AddressStreet = "Forestview";
ListingPrice = 600000;
MonthlyRent = 0;
Taxes = 2000;
Channel = Channel.Rosa;
}
static List<property> inventory = new List<property>
{
new property("19263","Collingham",24000,700,1744, Channel.Rosa),
new property("16003","Collingham",24000,700,1672, Channel.Rosa),
new property("13051","Bringard",24000,700,1305, Channel.Rosa),
new property("10409","Bringard",24000,650,1591, Channel.Rosa),
new property("10086","Marne",24000,650,1176, Channel.Rosa),
new property("10042","Peerless",24000,650,1313, Channel.Rosa),
new property("10736","Steel",30000,1000,1587, Channel.Mike),
new property("2010","Glendale",30000,1000,1587, Channel.Mike),
new property("2260","Blain",30000,1000,1587, Channel.Mike),
new property("3000","Fullerton",30000,1000,1587, Channel.Mike),
};
property addtolist= new property("864", "Alter", 30000, 650, 1600, Channel.Rosa);
inventory.Add(addtolist);
public static void userAddItem()
{
//I want to use the list here
}
public static void allItemsToFile()
{
//and here
}
} //end of house class bracket
You should think of your classes as objects. So your house class can just be a object that defines a house.
public class houses
{
public string AddressNumber { get; set; }
public string AddressStreet { get; set; }
public double ListingPrice { get; set; }
public double MonthlyRent { get; set; }
public double Taxes { get; set; }
public Channel Channel { get; set; }
}
Now, you want to make a list of properties. In your main class, you can do something like this;
private List<houses> properties = new List<houses>();
houses house1 = new houses();
house1.AddressNumber = "19263";
house1.AddressStreet = "Collingham";
house1.ListingPrice = 24000.0;
hosue1.MonthlyRent = 700.0;
house1.Taxes = 1744.0;
house1.Channel = Channel.Rosa;
properties.Add(house1);
Now you have a list of properties and you can access them as you need.
Foreach(houses h in properties)
{
Console.WriteLine("{0},{1},{2},{3},{4},{5}", h.AddressNumber, h.AddressStreet, h.ListingPrice, h.MonthlyRent, h.Taxes, h.Channel.toString());
}
Related
I have a class MechanicalData and in that i have list of objects and in the below function i am trying to form list of objects with values coming from input.
Mechanicaldata class looks like below
public class MechanicalData
{
public List<LibraryA170> AirflowsA170 { get; set; }
......
}
and the classes libraryA170 and LibraryAcoustic looks like as follows
public class LibraryA170 : AEIMasterBase
{
public string Category { get; set; }
public string SpaceFunction { get; set; }
[Column(TypeName = "varchar(32)")]
public DirectExhaust? DirectExhaust { get; set; }
.....
......
}
public class LibraryAcoustic : AEIMasterBase
{
public string Category { get; set; }
public string SpaceFunction { get; set; }
public double? NoiseCriteria { get; set; }
.......
}
and base class AEIMasterBase looks like as below
public class AEIMasterBase
{
public Guid Id { get; set; }
public MasterSection MasterSection { get; set; }
public List<string> NotesHTML { get; set; }
public bool? IsApproved { get; set; }
public Guid? InitialRevisionId { get; set; }
public Guid? LatestRevisionId { get; set; }
public int? Revision { get; set; }
}
Below i am trying to map all those fields with LINQ select
private static MechanicalData TransformedMechanicalData(MechanicalData sourceMechanicalData, Dictionary<string, MasterSection> masterSectionMappedLibrary)
{
return new MechanicalData
{
AirflowsA170 = sourceMechanicalData.AirflowsA170.Select(airflow170 => new LibraryA170
{
Id = airflow170.Id,
InitialRevisionId = airflow170.InitialRevisionId,
LatestRevisionId = airflow170.LatestRevisionId,
IsApproved = true,
Revision = airflow170.Revision,
NotesHTML = airflow170.NotesHTML,
SpaceFunction = airflow170.SpaceFunction,
Category = airflow170.Category,
MasterSection = masterSectionMappedLibrary["Library A170"],
........
}).ToList(),
Acoustic = sourceMechanicalData.Acoustic.Select(acoustic => new LibraryAcoustic
{
Id = acoustic.Id,
InitialRevisionId = acoustic.InitialRevisionId,
LatestRevisionId = acoustic.LatestRevisionId,
IsApproved = true,
Revision = acoustic.Revision,
NotesHTML = acoustic.NotesHTML,
Category = acoustic.Category,
SpaceFunction = acoustic.SpaceFunction,
......
}).ToList()
};
}
is there any way i can pass two objects to a method and map common properties inside that method and leave uncommon properties to be mapped inside the select statement while adding to the list.
I am looking for something like as below if possible
public static class ItemExtensionMethods
{
public static readonly Expression<Func<Item, MinimalItem>> MapToMinimalItemExpr =
source => new MinimalItem
{
Id = source.Id, // only common properties like id, revision, IsApproved
Property1 = source.Property1
};
}
below are some common properties
Id = airflow170.Id,
InitialRevisionId = airflow170.InitialRevisionId,
LatestRevisionId = airflow170.LatestRevisionId,
.......
Could any one please suggest any idea on this, Many thanks in advance
update getting below error
Given two expression tree's, you want to locate the two MemberInitExpression nodes, merge their MemberBinding's and swap any ParameterExpression.
class LocateBindings : ExpressionVisitor
{
public IEnumerable<MemberBinding> Bindings { get; private set; }
protected override Expression VisitMemberInit(MemberInitExpression node)
{
Bindings = node.Bindings;
return base.VisitMemberInit(node);
}
}
class MergeBindings : ExpressionVisitor
{
private IEnumerable<MemberBinding> bindings;
private ParameterExpression parameter;
public MergeBindings(IEnumerable<MemberBinding> bindings, ParameterExpression parameter)
{
this.bindings = bindings;
this.parameter = parameter;
}
protected override Expression VisitMemberInit(MemberInitExpression node)
=> node.Update(node.NewExpression,
node.Bindings.Concat(bindings)
.Select(VisitMemberBinding));
protected override Expression VisitParameter(ParameterExpression node)
=> parameter;
}
public static Expression<Func<P, D>> Merge<BP, P, B, D>(
Expression<Func<BP, B>> baseExpr,
Expression<Func<P, D>> derivedExpr
)
where D:B where P:BP
{
var locate = new LocateBindings();
locate.Visit(baseExpr);
var merge = new MergeBindings(locate.Bindings, derivedExpr.Parameters[0]);
return merge.VisitAndConvert(derivedExpr, "");
}
For example;
Expression<Func<[insert type], AEIMasterBase>> baseExpression = basearg => new AEIMasterBase
{
Id = basearg.Id,
InitialRevisionId = basearg.InitialRevisionId,
LatestRevisionId = basearg.LatestRevisionId,
IsApproved = true,
Revision = basearg.Revision,
NotesHTML = basearg.NotesHTML,
SpaceFunction = basearg.SpaceFunction,
};
Expression<Func<[insert type], LibraryA170>> derivedExpression = airflow170 => new LibraryA170
{
Category = airflow170.Category,
MasterSection = masterSectionMappedLibrary["Library A170"],
};
var merged = Merge(baseExpression, derivedExpression);
...
AirflowsA170 = sourceMechanicalData.AirflowsA170.Select(merged).ToList()
...
Trying to populate an ObservableCollection from a database using the Entity Framework. Everything was fine until I started working with linked tables.
I created the DeviceCategory and DeviceComplexity model, and now in the WyeModel I try to integrate them into the DeviceCategoryViewModel. Further, in DeviceCategoryViewModel, I indicated a request for taking information from the database, but I ran into a problem. How to fill in ObservableCollection with this information? I tried different ways, but it didn’t lead to anything, I just got more confused.
DeviceCategoriesViewModel
class DeviceCategoryViewModel
{
TechDContext dc = new TechDContext();
public int Device_category_id { get; set; }
public string Device_category_name { get; set; }
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public static DeviceCategoryViewModel DeviceCaterogyVM(DeviceCategory deviceCategory, DeviceComplexity deviceComplexity)
{
return new DeviceCategoryViewModel
{
Device_category_id = deviceCategory.Device_category_id,
Device_category_name = deviceCategory.Category_name,
Device_complexity_id = deviceCategory.Device_complexity_id,
Device_complexity_name = deviceComplexity.Device_complexity_name
};
}
public void FillDeviceDategories()
{
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new
{
Device_category_id = cat.Device_category_id,
Category_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
items = q;
deviceCategories = Convert(items);
}
public ObservableCollection<DeviceCategoryViewModel>
Convert(IEnumerable<object> original)
{
return new ObservableCollection<DeviceCategoryViewModel>(original.Cast<DeviceCategoryViewModel>());
}
private IEnumerable<object> items;
public IEnumerable<object> Items
{
get
{
return items;
}
}
private ObservableCollection<DeviceCategoryViewModel> deviceCategories;
public ObservableCollection<DeviceCategoryViewModel> DeviceCategories
{
get
{
FillDeviceDategories();
return deviceCategories;
}
}
DeviceCategory Model
[Table("device_categories")]
public class DeviceCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Device_category_id { get; set; }
public string Category_name { get; set; }
//[ForeignKey]
public int Device_complexity_id { get; set; }
public DeviceCategory()
{
}
public DeviceCategory(string name, int complexity_id)
{
Category_name = name;
Device_complexity_id = complexity_id;
}
}
DeviceCompexity Model
[Table("device_complexities")]
public class DeviceComplexity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public DeviceComplexity()
{
}
public DeviceComplexity(string name)
{
Device_complexity_name = name;
}
}
I now get an error in the conversion method
You'd try to cast your LINQ query result to ObservableCollection<DeviceCategoryViewModel> in separate Convert function.
Why not to directly collect your LINQ query result to ObservableCollection<DeviceCategoryViewModel>
Just use like this
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new DeviceCategoryViewModel // <= Note This Line
{
Device_category_id = cat.Device_category_id,
Category_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q);
OR if you want to get result after list then simply use q.ToList()
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q.ToList());
Let's say I have a class StockMarket which has a list of Companies.
class StockMarket : IStock
{
private static List<IObserverPush> observersPush;
private static List<IObserverPull> observersPull;
public static List<Company> Companies { get; private set; }
public StockMarket()
{
observersPush = new List<IObserverPush>();
observersPull = new List<IObserverPull>();
Companies = new List<Company>() { new Company("Unilever", "UNA", 47.72, 0.77, 1.63, -3.45, "135B"),
new Company("ING Groep", "INGA", 13.40, -0.07, -0.50, -12.38, "60.4B"),
new Company("ArcelorMittal", "MT", 29.50, 0.14, 0.48, 36.05, "54.6B"),
new Company("ASML Holding", "ASML", 167.40, 2.00, 1.21, 36.49, "53.3B"),
new Company("Heineken", "HEIA", 87.66, -0.02, -0.02, 2.80, "49B"),
new Company("RELX", "REN", 18.15, 0.17, 0.95, -0.22, "38.9B"),
new Company("Philips", "PHIA", 35.49, 0.17, 0.47, 7.61, "33.3B"),
new Company("Unibail Rodamco", "UL", 196.40, -0.15, -0.08, -16.78, "20.3B"),
new Company("Akzo Nobel", "AKZA", 75.68, -0.16, -0.21, 0.33, "19.4B"),
new Company("Altice", "ATC", 7.58, 0.16, 2.16, -66.30, "17.6B")};
Thread thread = new Thread(SimulateMarket);
thread.Start();
}
public void Subscribe(IObserverPull o)
{
observersPull.Add(o);
o.UpdateMarket();
}
public void Unsubscribe(IObserverPull o)
{
observersPull.Remove(o);
}
public void Subscribe(IObserverPush o)
{
observersPush.Add(o);
o.UpdateMarket(Companies);
}
public void Unsubscribe(IObserverPush o)
{
observersPush.Remove(o);
}
public void NotifyObservers()
{
foreach(IObserverPush o in observersPush)
{
o.UpdateMarket(Companies);
}
foreach(IObserverPull o in observersPull)
{
o.UpdateMarket();
}
}
public void SimulateMarket()
{
while(observersPush.Count + observersPull.Count > 0)
{
//randomly change property values of companies
//and notify the observers about the changes
}
}
}
Company class has some properties.
public class Company
{
public string Name { get; private set; }
public string Symbol { get; private set; }
public double Price { get; set; }
public double Change { get; set; }
public double ChangePercentageDay { get; set; }
public double ChangePercentageYear { get; set; }
public string Capital { get; private set; }
public Company(string name, string symbol, double price, double change, double changePercentageDay,
double changePercentageYear, string capital)
{
Name = name;
Symbol = symbol;
Price = price;
Change = change;
ChangePercentageDay = changePercentageDay;
ChangePercentageYear = changePercentageYear;
Capital = capital;
}
}
The Forms have references to the StockMarket and they use it to retrieve data about the companies and to display it.
Form 1
public partial class ConcreteObserverPush : Form, IObserverPush
{
private StockMarket stockMarket;
public ConcreteObserverPush()
{
InitializeComponent();
stockMarket = new StockMarket();
stockMarket.Subscribe(this);
}
public void UpdateMarket(List<Company> companies)
{
stockMarketListView.Items.Clear();
foreach(Company c in companies)
{
ListViewItem item = new ListViewItem(c.Symbol);
item.SubItems.Add(c.Price.ToString());
item.SubItems.Add(c.Change.ToString());
item.SubItems.Add(c.ChangePercentageDay.ToString() + "%");
stockMarketListView.Items.Add(item);
}
}
private void ConcreteObserverPush_FormClosing(object sender, FormClosingEventArgs e)
{
stockMarket.Unsubscribe(this);
}
}
Form 2
public partial class ConcreteObserverPull : Form, IObserverPull
{
private StockMarket stockMarket;
public ConcreteObserverPull()
{
InitializeComponent();
stockMarket = new StockMarket();
stockMarket.Subscribe(this);
}
public void UpdateMarket()
{
stockMarketListView.Items.Clear();
foreach (Company c in StockMarket.Companies)
{
ListViewItem item = new ListViewItem(c.Symbol);
item.SubItems.Add(c.Name);
item.SubItems.Add(c.Price.ToString());
item.SubItems.Add(c.Change.ToString());
item.SubItems.Add(c.ChangePercentageDay.ToString() + "%");
item.SubItems.Add(c.ChangePercentageYear.ToString() + "%");
item.SubItems.Add(c.Capital);
stockMarketListView.Items.Add(item);
}
}
private void ConcreteObserverPull_FormClosing(object sender, FormClosingEventArgs e)
{
stockMarket.Unsubscribe(this);
}
}
The problem is that if the Form gets the list of companies through the property on StockMarket it can change their state. However, I want only StockMarket to have the ability to change the state of the company.
So what would be the best way to share Company state with Form when requested and preventing the Form from modifying it.
I know that a possible solution would be to return clones of Company objects, but I believe there should be a better solution.
Any help is appreciated!
The general gist of this would be to make your Company object immutable. Then you would add methods to the StockMarket object to manipulate the Company list and replace entries with new ones when you want to change a value.
Here's a quick example put together in LINQPad of making the Company class immutable and adding an UpdatePrice method to the StockMarket class.
Whether you want to be able to manipulate the Companies property from outside the StockMarket can be handled by returning the list as ReadOnlyCollection so that it's size can't be manipulated by a consumer.
void Main()
{
var sm = new StockMarket();
sm.Companies.Add(new Company("Test", "TST", 50, 0));
sm.UpdatePrice("Test", 45);
var testCompany = sm.Companies.First(x => x.Name == "Test");
Console.WriteLine($"{testCompany.Name},{testCompany.Symbol},{testCompany.Price},{testCompany.Change}");
//Output: Test,TST,45,-5
}
class StockMarket
{
public List<Company> Companies { get; private set; } = new List<Company>();
public void UpdatePrice(string name, double price) {
var index = Companies.FindIndex(x => x.Name == name);
if(index >= 0)
{
var previous = Companies[index];
Companies[index] = new Company(previous.Name, previous.Symbol, price, price - previous.Price);
}
}
}
class Company
{
public Company(string name, string symbol, double price, double change) {
Name = name;
Symbol = symbol;
Price = price;
Change = change;
}
public string Name { get; }
public string Symbol { get; }
public double Price { get; }
public double Change { get; }
///...
}
This would be a solution:
Create the Company class as a Private Inner Class inside of the StockMarket class, that way it'd only be accessible inside of it, and then provide an interface that only includes the get of all the properties and make Company implement it. You would have to make StockMarket's Company list to be the Interface's type.
Any modification you'd have to do you'd do it by casting the interface's List objects into the original class type.
Example:
class Program
{
public static StockMarket stockMarket = new StockMarket();
static void Main(string[] args)
{
}
}
public interface ICompany
{
string Name { get; }
}
public class StockMarket
{
public StockMarket()
{
Companies = SomeWildFunctionThatRetrievesAllCompanies();
}
public void OneWildFunctionThatModifiesACompany()
{
Company dunno = (Company)Companies[0];
dunno.Name = "Modification Made Possible";
}
private List<ICompany> SomeWildFunctionThatRetrievesAllCompanies()
{
return new List<ICompany>(new List<Company>());
}
public List<ICompany> Companies { get; private set; }
private class Company : ICompany
{
public string Name { get; set; }
}
}
Try this:
class Company
{
public Company(Type type,string name,string symbol,double price, double change)
{
if (type.Name == "StockMarket")
{
Name = name;
Symbol = symbol;
Price = price;
Change = change;
}
}
private string Name { get; set; }
private string Symbol { get; set; }
private double Price { get; set; }
private double Change { get; set; }
///...
}
This will allow you to change the state only if the type is StockMarket
like:
class StockMarket
{
public List<Company> Companies { get; set; }
public StockMarket()
{
Companies = new List<Company>();
}
public StockMarket someMethod()
{
//You can change the state here
StockMarket s = new StockMarket();
s.Companies.Add(new Company(this.GetType(), "aa", "_", 123, 1234));
return s;
}
//...
}
Now you cannot change the state here:
public partial class Observer: Form
{
private StockMarket stockMarket;
public ConcreteObserverPull()
{
InitializeComponent();
stockMarket = new StockMarket();
//Here you cannot change the state
stockMarket.Companies.Add(new Company(this.GetType(), "aa", "_", 123,12));
}
//...
}
Sorry, I don't know C#, but as an idea, you can wrap returned entities with decorator or proxy, which will throw an exception in case of trying to modify state of a company.
Returning clones with fields set as readonly is the safest way to go.
In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);
I have observablecollection which i fill with textboxes on button click event. In my Project is one class where i have list >> public List _RoomNumber = new List(); i want to just send observablecollection value into _RoomNumber list. For example if observablecollection cotains this 4 values : 15, 20, 2323, 3232 i want _RoomNumber context be same so this : 15, 20, 2323, 3232
I hope my question is clear.
This my observablecollection :
ObservableCollection<CheckInData> _CheckInCollection = new ObservableCollection<CheckInData>();
public ObservableCollection<CheckInData> CheckInCollection
{
get { return _CheckInCollection; }
}
public class CheckInData
{
public string RoomNumber { get; set; }
public decimal Price { get; set; }
public string Currecny { get; set; }
public decimal Discount { get; set; }
public string CheckOut { get; set; }
public int TotalDay { get; set; }
public decimal TotalPrice { get; set; }
public int CheckOutYear { get; set; }
public int CheckOutMonth { get; set; }
public int CheckOutDay { get; set; }
public Boolean IncToday { get; set; }
}
this is how im trying to put in list. Problem is that observablecollection contains 102 and 305. _RoomNumber only gets value '1'. please help
private void btnPrintInvoice_Click(object sender, RoutedEventArgs e)
{
//This is Class where my List _RoomNumber is
DataToExcel.Invoice inv = new DataToExcel.Invoice();
foreach (CheckInData coll in CheckInCollection)
{
for (int i = 0; i < _CheckInCollection.Count; i++)
{
inv._RoomNumber.Add(coll.RoomNumber[i].ToString());
}
}
}
You need to make small modification. Try this:
private void btnPrintInvoice_Click(object sender, RoutedEventArgs e)
{
//This is Class where my List _RoomNumber is
DataToExcel.Invoice inv = new DataToExcel.Invoice();
foreach (CheckInData coll in CheckInCollection)
{
inv._RoomNumber.Add(coll.RoomNumber.ToString());
}
}
You don't need to access RoomNumber with index. It is not a collection.
You can use
var roomnumbers = CheckInCollection.Select(x => x.RoomNumber);
inv._RoomNumber = new List(roomnumbers);
Or if you want to reuse the existing List instance,
inv._RoomNumber.Clear();
inv._RoomNumber.AddRange(roomnumbers);
but this seems to be not your case.
Note that in your code, your both inner and outer loops iterate over the same collection :-)
using System.Linq;
...
ObservableCollection<string> ListA = new ObservableCollection<string>();
List<string> ListB = ListA.ToList<string>();