Accessing a List of Class objects - c#

I'm trying to get the following to work:
A class called Caption, where I populate a List - adding Items to the Class list
I then want to reference the list of class values, in a lookup method
public class Caption
{
readonly CaptionKey _CaptionKey; //Enum list
readonly string _Description;
public Caption(CaptionKey captionKey, string description)
{
_CaptionKey = captionKey;
_Description = description;
}
public CaptionKey CaptionKey { get { return _CaptionKey; } }
public string Description { get { return _Description; } }
}
Here is the class that creates the class list
public class InitCaptions
public static List<Caption> _Captions = new List<Caption>();
// the class access I need
public static string LookupCaption( CaptionKey )
{
//? How to return the description for
}
The problem is with referencing the list of classes from another class and process.
I can see the values in the debugger are there-
System.Collections.Generic.List<MyNamespace.Controllers.Captions>
I'm just not sure how to reference it properly.
I should add - this is a MVC solution - so the List is created in the application startup, but the reference call is done from a report - using ReportViewer. the List shows in the code using Intellisense, but when run - the List is not there.

Assuming a Simple Dictionary<> won't suit your needs (for reasons you have not specified),
then to find and return an item from a List you can use the List.Find method, which takes a delegate and is used like this:
Caption foundItem = _Captions.Find(delegate (Caption obj) { return obj.Description.equals("Find this Description"); });
If there is more than one, then it will return the first it finds.
There is also the FindAll(....) version of this which will return a new list of all matches items.

Related

How i can get object in class List

I created my class
class TxtEmail
{
public TxtEmail(string firtFirstmail, string domain)
{
this.Firstmail = firtFirstmail;
this.Domain = domain;
}
public string Firstmail { get; set; }
public string Domain { get; set; }
public string RetOneString()
{
return Firstmail + "#" + Domain;
}
}
Then my class add to List Class
class EmailDP : List<TxtEmail>
{
List<TxtEmail> txtemail = new List<TxtEmail>();
public void Add(string path)
{
txtemail.Add(new TxtEmail("user1", "google.ru"));
txtemail.Add(new TxtEmail("user5555", "google.com"));
txtemail.Add(new TxtEmail("user252", "outlook.com"));
txtemail.Add(new TxtEmail("user3", "gmail.com"));
}
another methods ......
But then i created object my classes, he show 0 Count, Why? Where i make mistake and how i can get object in it?
EmailDP em1 = new EmailDP();
MessageBox.Show(em1.Count.ToString()); -> this show 0
foreach (var myob in em1)
{
MessageBox.Show(myob.RetOneString());
}
You have two lists involved:
The class EmailDP itself derives from List<TxtEmail> and is therefore a list whose count you are displaying
The internal list txtemail to which you actually add the items, leaving EmailDP itself empty.
Change your class, so that it encapsulates the inner list.
class EmailDP
{
private readonly List<TxtEmail> _txtemail = new List<TxtEmail>();
public void Add(string path)
{
_txtemail.Add(new TxtEmail("user1", "google.ru"));
_txtemail.Add(new TxtEmail("user5555", "google.com"));
_txtemail.Add(new TxtEmail("user252", "outlook.com"));
_txtemail.Add(new TxtEmail("user3", "gmail.com"));
}
public int Count => _txtemail.Count;
public IEnumerable<TxtEmail> EmailTexts => _txtemail;
// ... other methods
}
And of course you have to call Add at least once...
EmailDP em1 = new EmailDP();
em1.Add("some path");
em1.Add("another path");
MessageBox.Show(em1.Count.ToString());
foreach (var myob in em1.EmailTexts)
{
MessageBox.Show(myob.RetOneString());
}
If you override ToString instead of creating a method RetOneString, you have the advantage that the TxtEmail objects will be displayed automatically at several places. I.e. in the debugger, in listboxes or in Console.WriteLine.
public override string ToString()
{
return Firstmail + "#" + Domain;
}
Your EmailDP is-a List and also has-a List and I don't think you mean for both of those to be true. It's a question of inheritance vs composition. Do you need your class to be a list or can it contain a list instead?
If you want your class to be-a List, then in your add method, you can do:
this.Add(new TxtEmail("user1", "google.ru")); ...
If you want your class to contain-a List then you can remove the inheritance of List
class EmailDP
{
...
And then make your list public so it is accessible:
public List<TxtEmail> txtemail = new List<TxtEmail>();
And then get the count from the list contained within:
MessageBox.Show(em1.textemail.Count.ToString());
Hope that helps.
You need to call the Add Method which fills your array.
Also do not inherit the List as you do not need this.
EmailDP em1 = new EmailDP();
em1.Add(string.Empty);
MessageBox.Show(em1.Count.ToString()); -> You will get items you added in the Add Method
foreach (var myob in em1)
{
MessageBox.Show(myob.RetOneString());
}

Getting an object's list from inside another object

This is the layout
House -> HouseDef -> Room -> Door
L---> Windows
The problem is that any class may or may not have lists and nested classes like HouseDefinition does. The point is it should be flexible to handle any of these three cases for class variations:
1. hasList,
2. hasNestedObject with List inside that Nested Object
3. Has neither a List nor Nested class
Example of 1 being a Room class which contains a Window List
Example of 2 like House Class
Example of 3 like a Window Class
I have these two classes that I want to access generically from another class. I want to be able to get the Rooms List in House Definition by access of House class stored as an object in MyTreeNode. How can I do this not bound by types, or polymorphic to support a deeper hierarchy level in the future?
public class House
{
string name;
HouseDefinition definition;
public string Name() { return name; }
public HouseDefinition Definition {get {return definition;}}
public House(string name,HouseDefinition definition)
{
this.name = name;
this.definition = definition;
}
}
public class HouseDefinition
{
private List<Room> rooms = new List<Room>();
string type;
public List<Room> Rooms { get { return rooms; } }
public Room this[int i] { get { return rooms[i]; } }
public HouseDefinition(string type)
{
DefaultLayout();
this.type = type;
}
}
public class MyTreeNode : TreeNode
{
string label;
IEnumerable items;
bool hasList;
object item;
public string Label { get {return label; } }
public IEnumerable Items { get { return items;} }
public object Item { get { return item; } }
public bool HasList { get { return hasList; } }
public MyTreeNode(object item)
{
this.item = item;
label = item.ToString();
hasList = false;
}
public MyTreeNode(object item, IEnumerable Items)
{
this.item = item;
label = item.ToString();
hasList = true;
}
}
I think your classes look fine, but I would remove HouseDefinition, since those properties just seem like House to me. If you want to practice inheritance, you could create an IBuilding interface that forces House, Mansion, Shack to implement GetRooms() or something like that. A couple other things:
Your TreeNode class should be using generic types like public MyTreeNode(T item)
You should check out autoimplemented properties - the public fields automatically create private backing fields, so you don't need to create a private field and a getter like you did here: public object Item { get { return item; } }
it's considered bad practice to use the "object" type, so you should convert those to the generic types mentioned above
Good luck, your code is looking good so far!

How to add a class property to a list of instances

I'm newbie in C#. Perhaps this is too simply to resolve but I'm really away of the solution.
I have this class:
public class TestSetups : TabelaCtset
{
public IList<TabelaCtsca> ValSetup { get { return m_valsetup; } }
private static List<TabelaCtsca> m_valsetup;
/// Constructor
public TestSetups(IDefinitionList dlist)
: base(dlist)
{
m_valsetup = new List<TabelaCtsca>();
}
}
I have another class called TestCase
public class TestCase : TabelaCttes
{
public IList<TestSetups> Setups { get { return m_setups; } }
private List<TestSetups> m_setups;
...
testcase.m_setups = new List<TestSetups>();
defs = gdl.GetDefinitions(testcase);
while (defs.MoveNext())
{
TestSetups testsetup = new TestSetups(defs);
IDefinitionList valsetup = gdl.GetDefinitions(testsetup);
{
TabelaCtsca ctsca = new TabelaCtsca(valsetup);
testsetup.ValSetup.Add(ctsca);
}
testcase.Setups.Add(testsetup);
}
return testcase;
...
}
I want to put all ctsca values in a ValSetup list. All works fine, except this line testcase.Setups.Add(testsetup);: I have the the properties of TestSetups class but my ValSetup property is always empty, when my while goes to another iteration.
Sorry for this weird explanation. I'm able to explain in more detail.
Update: In this situation, I store in each TestSetup just the last ValSetup value and not all the ValSetup of each TestSetup.
You've made m_valsetup a static property, but you're re-initializing every time you create a new instance of TestSetups. If you want it to be a shared list across all instances of TestSetups, then you could use a property initializer like this:
private static List<TabelaCtsca> m_valsetup = new List<TabelaCtsca>();
And remove the initialization of it in the constructor.
If you didn't intend for the list to be shared, then just remove the static keyword from its definition.

Populate List with Json file

I have a List of Items. Item is an object with multiple constructors, thus an item can be created in several forms.
Example of class Item with two constructors.
public class Item
{
public string name = "";
public int age= 0;
public int anotherNumber = 0;
public Item(string iName, int iAge)
{
name = iName;
age= iAge;
}
public Item(string iName, int iAge, int iAnotherNumber)
{
name = iName;
age= iAge;
}
}
I have then a Json file in the form of:-
[{"name":"Joseph","age":25},{"name":"Peter","age":50}]
I'm using the below method to read file and populate list using Newtonsoft.Json API.
public List<Item> ReadJsonString()
{
List<Item> data = new List<Item>();
string json = File.ReadAllText("\\path");
data = JsonConvert.DeserializeObject<List<Item>>(json);
return data;
}
If I have only one constuctor in the Item class (example the constructor that takes 2 arguments) this method works fine and I am able to populate the list. However when I add the second constructor in class Items(since I want to be able also to read Json files with the third attribute..
Example:-
[{"name":"Joseph","age":25, "anotherNumber": 12},{"name":"Peter","age":50, "anotherNumber": 12}]
The ReadJsonObj method fails with error "Unable to find a constructor to use for type Item". I can fix this issue by creating multiple class Item (e.g. ItemA, ItemB),one that takes three variables and the other that takes two variables. However I would like to have only one Item class.
I cannot find out why this is happening and how to fix such an issue.
You can use properties instead of regular fields and constructor initialization.
public class Item
{
public string name {get;set;}
public int age {get;set;}
public int anotherNumber {get;set;}
}
Thus you will cover both deserialization cases.

Is it legal XML to have two different List<> objects using some sort of level identifier to separate and identify them?

I am thinking about using an XML file to hold multiple types of data. Let’s say for this example we have two lists. I see plenty of examples that serializes a single List to an XML root, but I haven’t found the correct keywords to find examples of embedding two.
I’d like to see some C# code that decodes such a structure.
As an example the lists might have classes that look like the following.
public class Item
{
public string Name;
public int Count;
public bool Active;
public override string ToString()
{
return String.Format("{0,-10} {1,10} {2:True,2:False}", Name, Count, Active);
}
}
public class Item2
{
public string Name;
public string Category;
public int Length;
public int Height;
public override string ToString()
{
return Name;
}
}
Create a new class and put both of your lists inside that class:
public class AllTheThings
{
public List<Item> Items;
public List<Item2> Items2;
}
Then serialize that class. Also note that you can do this as many levels deep as you want. For instance Item could have a list inside of it as well.

Categories