Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am pretty sure that somewhere this question was answered but i could not find it.
I am looking up Objects from a list with name and quantity. The same Item can come up several times with different quantities. I want to add up the quantities.
bool addtolist = true; //the item is not part of the list
Item currentItem = FindItem(currentMats.Name); //Find the Item in the Catalogue
currentItem.Calc(currentMats.NeededQuantity, product.Runns, product.Level + 1); //Add quantities ect
CompleteList.Add(currentItem);
Here is the problem:
The first time the Algorithm runs all is ok.
The Problem comes up at the second run: the quantity is overridden the moment it hits line 2.
How can i force a new object and not a reference to the one in the storage?
A new instance of an object is only created when the new keyword is used. To get a copy, you'll have to create one
You could create a copy constructor and then a clone method on Item
public Item(Item otherItem){
variable1 = otherItem.variable1;
variable2 = otherItem.variable2;
...
}
public Item Clone(){
return new Item(this);
}
Then when you get the item, clone it
bool addtolist = true; //the item is not part of the list
Item currentItem = FindItem(currentMats.Name).Clone(); //Find the Item in the Catalogue
currentItem.Calc(currentMats.NeededQuantity, product.Runns, product.Level + 1); //Add quantities ect
CompleteList.Add(currentItem);`
Basically what you are doing is a histogram. LINQ has a built in method called GroupBy() that does this. See sample code below:
public class Material
{
public Material(string name, int quantity)
{
this.Name=name;
this.Quantity=quantity;
}
public string Name { get; private set; }
public int Quantity { get; private set; }
}
class Program
{
static void Main(string[] args)
{
List<Material> list=new List<Material>();
list.Add(new Material("AAA", 10));
list.Add(new Material("BBB", 20));
list.Add(new Material("CCC", 5));
list.Add(new Material("AAA", 5));
list.Add(new Material("CCC", 20));
Console.WriteLine("{0,6} {1,6}", "Mat", "Qty");
foreach(var item in list.GroupBy((mat) => mat.Name))
{
Console.WriteLine("{0,6} {1,6}", item.Key, item.Sum((mat) => mat.Quantity));
}
// Mat Qty
// AAA 15
// BBB 20
// CCC 25
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I tried to add an item in myList inside foreach loop:
I summarized the problem, Let's consider the EmployeeInfo has 1000 records then the HasValue did not adding items.
List<bool> HasValue = new List<bool>();
foreach(var list in EmployeeInfo)
{
if(list.Count() > 0)
{
HasValue.Add(true);
}
else
{
HasValue.Add(false);
}
}
Does this help you get closer to your answer?
public class EmployeeInfo {
public List<String> TheList { get; } = new List<String>();
}
public void Test(){
var employeeInfo = new EmployeeInfo();
var hasValues = employeeInfo.TheList.Count( list => list.Any() );
var noValues = employeeInfo.TheList.Count - hasValues;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is there a way to write this so I don't have to explicitly declare the field _D?
How do I get around the = new List<T>() when the class is implemented?
What I have:
class c {
private List<T> _D = new List<T>();
public List<T> D { get { return _D; } set { _D = value; } }
}
What I want:
class c {
public List<T> D { get; set; }
}
Wouldn't it be better to declare a constructor to assign the property a List<T>? As in:
class c {
c() { D = new List<t>(); }
public List<t> D { get; set; }
}
What are today's best practices when implementing properties and assigning initial values?
All three are technically correct. I found the first in a bit of code I'm taking over. I can't find any purpose behind the original code that declares all the property backing fields. I thought declaring backing fields was not a best practice since c# v3 .. except when you are actually going to use the private field somewhere in the class's methods, which isn't happening here.
You could look at assigning the initial List<> to the property as 'Using the property somewhere in the class.'
Or you could look at it as 'Pointless, do it like my third example instead.'
Which is generally regarded as best practice these days?
Since C# 6 you can do it this way:
public IList<int> Prop1 { get; set; } = new List<int> { 1, 2, 3 };
There are a few ways to achieve the same thing in .NET as well as best practices and recommendations. It all depends on your requirements and responsibilities for the object and properties. I saw a comment with a link to the programming guide which is excellent. These are just a few more examples.
public class C<T>
{
public List<T> D { get; set; } = new List<T>();
}
public class C2
{
public IReadOnlyList<int> D { get; private set; }
public C2()
{
D = new List<int>();
}
}
public class C3
{
private List<int> _d = null;
public List<int> D
{
get
{
return _d ?? new List<int>();
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to print all the products with a price between 10 and 50 euro.
I have created 2 products in main and I call the method from the class Product in order to make the verification.But it gives me the else branch everytime, "No products".I understand what I'm doing wrong, I create an object reference from the class Product, then I call the method but it gives me the wrong output because in the method I create another object and for this object this price is 0 so it shows me that thing.
But how can I resolve this?
Here there are the classes:
the product class:
class Product
{
public int ProductId;
public string SKU;
public string Name;
public decimal Price;
public string Description;
public string Producer;
public virtual decimal GetPrice()
{
return Price;
}
public virtual String GetName()
{
return Name;
}
public void PrintPrice()
{
Product f = new Product();
if (f.GetPrice() > 10 && f.GetPrice() < 50)
Console.WriteLine("Product: {0}", f.GetName());
else
Console.WriteLine("No products priced between 10 and 50 lei.");
}
public Product() { }
the main where I ve been creating the objects:
static void Main(string[] args)
{
Product f = new Food(1, "green", "Papa", 15, "Good Quality", "Sana");
Product f1 = new Food(2, "white", "Papa1", 45, "Bad Quality", "Ariel");
f.PrintPrice();
f1.PrintPrice();
}
and I have also the food class but it inherits only the Product class so it's not relevant here.So what can I do?Thank you.
public void PrintPrice()
{
Product f = new Product();
....
}
At the moment, f is a new Product without any properties (including no price)
You should do something like
public void PrintPrice()
{
if (this.GetPrice() > 10 && this.GetPrice() < 50)
Console.WriteLine("Product: {0}", this.GetName());
else
Console.WriteLine("No products priced between 10 and 50 lei.");
}
You did not assign a value to the Price, so it's 0 and then you have the "No products"..try to assign a value to the product first
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a Generic Class Report.
class Report<TValue1, TValue2>
{
public List<TValue1> AvailableValues { get; private set; }
public List<TValue2> DefaultValues { get; private set; }
public void SetValues(List<TValue1> availableValues, List<TValue2> defaultValues)
{
AvailableValues = availableValues;
DefaultValues = defaultValues;
}
}
From client Report class gets instantiated like shown below.
static void Main(string[] args)
{
List<String> names = new List<String>();
names.Add("asdf");
names.Add("asd");
List<Int32> ids= new List<Int32>();
ids.Add(1);
ids.Add(2);
Report<String, Int32> report1 = new Report<string, int>();
report1.SetValues(names, ids);
List<Boolean> names1 = new List<Boolean>();
names1.Add(false);
names1.Add(true);
List<Int32> ids2 = new List<Int32>();
ids.Add(11);
ids.Add(12);
Report<Boolean, Int32> report2 = new Report<Boolean, Int32>();
report2.SetValues(names1,ids2);
}
Now i want to Keep report1 and report2 instance in a collection so that they can be consumed later.
Please suggest how to store them and get report instances later in efficient way.
Since there is nothing incommon between the types you need to store them into a collection of objects.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a test class that I created and I want to be able to create multiple instances of it. Then I want to use foreach to iterate thru each instance. I have seen several forums that show IEnumerate but being a very newbe they have me confused. Can anyone please give me a newbe example.
My class:
using System;
using System.Collections;
using System.Linq;
using System.Text
namespace Test3
{
class Class1
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
}
Thanks
Do you need to enumerate through multiple instances of your type, or create a type that is itself enumerable?
The former is easy: add instances to a collection, such as List<T>() which implement IEnumerable<T>.
// instantiate a few instances of Class1
var c1 = new Class1 { Name = "Foo", Address = "Bar" };
var c2 = new Class1 { Name = "Baz", Address = "Boz" };
// instantiate a collection
var list = new System.Collections.Generic.List<Class1>();
// add the instances
list.Add( c1 );
list.Add( c2 );
// use foreach to access each item in the collection
foreach( var item in list ){
System.Diagnostics.Debug.WriteLine( item.Name );
}
When you use a foreach statement, the compiler helps out and automatically generates the code needed to interface with the IEnumerable (such as a list). In other words, you don't need to explicitly write any additional code to iterate through the items.
The latter is a bit more complex, and requires implementing IEnumerable<T> yourself. Based on the sample data and the question, I don't think this is what you are seeking.
How do I implement IEnumerable?
IEnumerable vs List - What to Use? How do they work?
Your class is just a "chunk of data" - you need to store multiple instances of your class into some kind of collection class, and use foreach on the collection.
// Create multiple instances in an array
Class1[] instances = new Class1[100];
for(int i=0;i<instances.Length;i++) instances[i] = new Class1();
// Use foreach to iterate through each instance
foreach(Class1 instance in instances) {
DoSomething( instance );
}