Add foreach to my class [closed] - c#

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 );
}

Related

Nested list getter and setter c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have this nested list :
public List<List<string>> pcList = new List<List<string>>();
How can I create getters and setters for it?
I have tried everything out there on the internet and nothing seems to work
Thx!
EDIT:
So, In class Pc I have this code:
class PC
{
public List<List<string>> pcList = new List<List<string>>();
public List<string> subList = new List<string>();
}
so the pcList is the "parent" list and the sublist is actually the place where I add each pc with its info.
I have a method where I populate the lists. Then I want to use an object of this class in another class called X, let's say.
I have tried to simply access the lists by using object.ListName but it doesn't work.
You can use auto property - just add {get;set;} (note that usually properties are upper case)
public List<List<string>> PcList {get;set;}
public List<List<string>> pcList { get; set; } = new List<List<string>>();
This is a variable.
If you want a property declare it like:
public List<List<string>> pcList {get;set;}

c# class declaration of properties [closed]

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>();
}
}
}

Copy a static field [closed]

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 9 years ago.
Improve this question
I have a class in which I operate some methods.
public class MyClass
{
public static List<ObjectA> MyField;
public static Object MyMethod()
{
List<ObjectA> anotherObjectA = new List<ObjectA>();
// I do something with anotherObjectA...
// after processing something now I want to keep the current status of anotherObjectA to MyField:
MyField = anotherObjectA;
// and now I want to work just with anotherObjectA. The problem is that whatever I work with anotherObjectA it changes also MyField
}
}
How can i achieve what I am trying to do
You can do
MyField = new List<ObjectA>(anotherObjectA);
This will create a copy of the list. However, any changes to the objects in the list will be visible in both. You'll have to decide for yourself how deep your copy has to be. If you really want a deep copy, you'll need to provide a mechanism for ObjectA to make a copy of itself, iterate over the original list, and add a copy of each object to the target list.
MyField and anotherObjectA reference same object. So if you change MyField it also changes anotherObjectA.
So First you need to create two List objects:
MyField = new List<ObjectA>(anotherObjectA);
This will create two list objects but the ObjectA objects inside the list are still referencing to the same.
MyField.First() == anotherObjectA.First() // returns true;
If you want to make a complete copy you also need to create a copy of objects inside anotherObjectA
public class ObjectA
{
public ObjectA() { } // Normal constructor
public ObjectA(ObjectA objToCopy) { /* copy fields into new object */ }
}
MyField = anotherObjectA.Select(obja => new ObjectA(obja)).ToList();
with this solution, changing objects inside MyField will not affect objects inside anotherObjectA unless ObjectA also contains reference types.

How to get a list of variables in a class in C# [duplicate]

This question already has answers here:
How to list all Variables of Class
(6 answers)
Closed 9 years ago.
How do I get a list of all the variables in a class, to be used in another class to indicate which Variables will and can be changed by it for example. This is mainly for not having to rewrite a enum when some variables are changed or added.
Edit:
I want to create a class that has some stats that can be modified (Main), and another type of class (ModifyingObject) that has a list of all the stats that it can change and by how much. I want to easily get the variables of the main class, and add a list of which variables does the modifying class change. if I have let's say 10 variables for different stats how can I easily list all the stats the ModifyingObject class can change in the Main class.
public class Main{
float SomeStat = 0;
string SomeName = "name";
List<ModifyingObject> objects;
bool CanModifyStatInThisClas(ModifyingObject object){
//check if the custom object can modify stats in this class
}
}
public class ModifyingObject{
....
}
You can use reflection.
Example:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
From here: How to get the list of properties of a class?
Properties have attributes (properties) CanRead and CanWrite, which you may be interested in.
Documentation: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx
Your question is a little vague, though. This may not be the best solution... depends heavily on what you're doing.

Add to a List from two Classes in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a list in one class. And I need to populate the list from another class. Then I need to access the list one or two other classes. I don't want to use static list. How is this done in C#. I tried my best. But not successful. Can anybody show example?.
use get I would suggest
This is where the list is
class A
{
private list<Objects> myList = new list<Objects>();
public list<Objects> getList()
{
return myList;
}
}
This is where you want to use it
class B
{
private list<Objects> myNewList = new list<Objects>();
A a = new A();
public void setList()
{
myNewList = a.getlist();
}
}
Something like this. Remember same namespace for classes to know each other, if in different files
This sounds like a job for a public property.
// I'm assuming a List of strings, fix accordingly
public class A
{
//Not autoimplemented to ensure it's always initialized
private List<string> items = new List<string>();
public List<string> Items
{
get { return items; }
set { items = value; }
}
}
public class AnyoneElse
{
void someMethod()
{
A someVar = new A();
someVar.Items.Add("This was added from outside");
MessageBox.Show(someVar.Items.First());
}
}
Access modifiers should be tweaked appropriately (they depend on your namespace structure, mostly. Also, are the class and the consumers in the same assembly or not ? Anyway, the point should be clear enough).
This is a basic example of what you need
public class YourOriginalClass
{
/// <summary>
/// The list you want to access
/// </summary>
public List<YourType> YourList {
get;
set;
}
}
// Here another class where you can use the list
public class YourSecondClass
{
public void EditMyList()
{
YourOriginalClass test = new YourOriginalClass();
test.YourList = new List<YourType>();
// then you can populate it
}
}

Categories

Resources