I have a two class properdata and pprosecnddata both classes having property
I want to access product property from properdata class list object. How is it possible,below is my sample code
pupilc class ProperData
{
public string code{get;set;}
public List<ProSecndData>Secnd{get;set;}
}
public class ProSecndData
{
public string product{get;set;}
}
I am trying to call property like that
class Program
{
static void Main(string[] args)
{
ProperData.Secnd.Product = "Hello";
}
}
you cannot directly access property of Secnd as it is a list
you need to iterate or select the index of the List<Secnd>
you must initialize Secnd first and Secnd should have items in the list
properData.Secnd = new List<ProSecndData>();
so it can be access via
foreach(var second in properData.Secnd)
{
second.product = "hello";
}
//or
for(var i = 0; i < proderData.Secnd.Count(); i++)
{
properData.Secnd[i].product = "hello";
}
//or
var index = //0-length of list;
properData.Secnd[index].product = "hello";
if you want to have items first then add first on your Secnd List
properData.Secnd = new List<ProSecndData>();
properData.Secnd.Add(new ProSecndData{ product = "hello"});
then you now can iterate the list by using methods above
You are trying to access list as a single object, which is not possible.
you need to create single instance of your list class and then you can add string in that single instance.
properData.Secnd = new List<ProSecndData>();
ProSecndData proSecndData = new ProSecndData();
proSecndData.product = "Hello";
properData.Secnd.Add(proSecndData);
Actually I know the answer already, you have not created a constructor to initialise your List.
I'm guessing you get a object null ref error?
Create the constructor to initialise your list and it should be fine.
But in future, please post the error message (not the whole stack, just the actual error) as well as all the code required to repeat the issue. Otherwise you run the risk of getting your question deleted
(It should be deleted anyway because it could be considered a "what is a null ref err?" question).
Also you are accessing an item in a list like the list is that item (should be more like: ProperData.Secnd.elementAt(0).product, please also note the capitalisation of 'product' in the model vs your code.
Related
public class LIST
{
public double num;
public double longi;
public double ux;
public double vy;
}
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
L1.ux= // I take l1.ux from stream reader by reading a file and made this
for
L1.vy=.. the other parameters
L1.longi=..
L1.num=....
LIST1.Add(L1)
Here my problem is ı made a list that contains 4 parameters. But ı want to find just one parameter value for instance L1.num how can I take this value from a list?
var indexOfLISTObject = 1 //you need to know which object from LIST1 you want to use
var numParamOfLISTObject = LIST1[indexOfLISTObject].num;
Please Don't name your object LIST. It will create readability issues down the line for you. Name the object what a particular item in your list will represent.
To access a particular property from an item in list you can do following
List l1 = new list();
//Add items ...
//Print property from particular index
Console.WriteLine(l1[index].propertyname);
Put the paremeters inside a list one by one.
in your example you want the parameter num.
List parameterNum = new List();
parameterNum = l1.Select(x => x.Num).ToList();
parameterNum has now the list of Num from l1 list.
If you mean to find/search for a particular value, you could also use System.Linq. For example if you would like to find a member where num is set to 2, you could do this:
LIST1.Where(item=>item.num==2).FirstOrDefault()
According my Understanding If you want to Get objects that contain with specific parameter
then you can use this code
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
var SearchedValue= List1.where(x=>x.num==L1.num).tolist();
if you want just L1.num value then you can use this line (if searched record will 1 then you should use this)
var SearchedValue= List1.where(x=>x.num==L1.num).FirstOrDefault().num;
you can use
LIST1[index].propertyname //index is index of list element and propertyname is the name of property you want to access
I have a class which have a list
public static List<bar> tempList = new List<bar>();
public static Foo foo = new Foo();
public class bar(){
public string name;
public int age;
}
public class Foo(){
public List<bar> lBar = new List<bar>();
}
I have several textbox controls: age1, age2
on textChange on each control a create a new object
/*------------------------------------------------------------------
Following code: I want runtime calculation for a logic i did with age.
also need to create a new object using the inputs
------------------------------------------------------------------*/
age1_textChaned(...){
createObj( );
}
age2_textChaned(...){
createObj( );
}
private void createObj(){
if(tempList.Count != 0)
tempList.Clear();
if(age1.Text != "")
tempList.Add(new bar("name1", Convert.ToInt32(age1.text));
if (age2.Text != "")
tempList.Add(new bar("name2", Convert.ToInt32(age2.text));
}
Then i have a button btn1 which will create the object then clear the content of textbox.
btn1_Click(...){
foo.lBar = tempList;
clearFields(); //here lies the question, once i clear the fields,
//somehow it is still affecting the values in foo.lBar;
}
private void clearFields(){
age1.Text = "";
age2.Text = "";
}
so when i do this
btn2_Click(...){
foreach(bar b in foo.lBar){ //foo.lBar is empty i dont know why
...
}
}
my current solution on btn1_click i have this
foreach(bar b in tempList)
foo.lBar.Add(b); // instead of foo.lBar = tempList
is the foo.lBar = templist causing these changes?
snippet is only a simpler version of an entirely different project.
Objects in C# are passed around by reference unless specified otherwise.
For example, here is the code you are running and how it works behind the scenes :
// create a new location in memory and refer to it using the variable tempList
public static List<bar> tempList = new List<bar>();
// add a new item to the list
tempList.Add(new bar("name1", Convert.ToInt32(age1.text));
// make the variable foo.lBar to also refer to the same spot in memory as tempList
foo.lBar = tempList;
// clear the spot in memory containing the list
tempList.Clear();
That last line affects both the tempList variable and the foo.lBar variable because they both refer to the same location in memory.
The solution to avoid this is to create a new copy of an object in memory so the two variables are pointing to two separate instances in memory, and clearing one does not clear the other.
That is why your current solution works
// add the memory location of each item in tempList to foo.lBar's list
foreach(bar b in tempList)
foo.lBar.Add(b);
Note that if you call tempList.Clear() it will only clear the memory references being stored in tempList, however the actual objects will still exist in memory elsewhere.
Also with this solution if you did something like this :
tempList[0].name = "A changed name";
it would change the name property of the item in the foo.lBar list as well, since they both share the same reference in memory.
When running the following code I receive an exception "CypherTypeException: Collections containing mixed types can not be stored in properties." - What am I doing wrong, and what needs to change to make it work?
var wordObjs = new List<object>();
foreach (string word in WordGroups.GetAllWords())
{
wordObjs.Add(new { Value = word});
}
GraphClient.Cypher
.Create("(word:Word {words})")
.WithParam("words", new { words = wordObjs})
.ExecuteWithoutResults();
One solution would be use a concrete class
private class Value {
public string Value {get;set;}
}
and use new List<Value>() instead, I think the client is having trouble with the anonymous nature of your List.
I have an issue with trying to modify a list of Transactions within a foreach. I have created copies of the list passed into my method, made it read only, and yet when I try to change a value within any of the lists it changes that value within them all. Some type of memory link? I am unsure how to resolve this issue.
My program starts by declaring a class called Transaction (which is a generic class having Name, Value, Formatting), then I have subClasses :Transaction. I create a TransList (from public class TransList : IEnumerable) which has an object instance of each subClass. So a TransList would include a class named TranID, Amount, OrderID, Time, CardType, Comment1, Comment2. Each value of these subclasses could be string, decimal, DateTime. After that a list of TransParts is created it is then put into a larger list called processTrans.
So Comment2 is the element with a payment citation number and if there is more than one number in there I want to separate that into more than one TransList add those new TransLists to processTrans and remove the non-separated one. From my code below, having tried every strategy, run-time modification occurs to not only the intended processTrans but also to tempProcessTrans, addOn, tran, tranPart.
If processTrans that is passed into method looks like this in the debugger locals
processTrans [0] _Items TranID.Value = SD234DF and Comment2 = adf;wer;
Then the output should be
processTrans [0] _Items TranID.Value = SD234DF-1 and Comment2.Value=adf
processTrans [1] _Items TranID.Value = SD234DF-2 and Comment2.Value=wer
I currently get
processTrans [0] _Items TranID.Value = SD234DF-1-2 and Comment2.Value=wer
processTrans [1] _Items TranID.Value = SD234DF-1-2 and Comment2.Value=wer
public static List<TransList> SeperateMultiCitations(List<TransList> processTrans) //change TransList seperating Multiple Citations
{
List<int> indexes=new List<int>();
IList<TransList> tempProcessTrans = processTrans.AsReadOnly(); //this didn't help
List<TransList> addOn= new List<TransList>(); //copy list didn't stop from changes to occur in processTrans at same time
foreach (TransList tran in tempProcessTrans.ToList())
{
TransList copyTransList = tran;
foreach (Transaction tranPart in tran.OfType<Comment2>())
{
if (new Regex(";.+;").IsMatch((string)tranPart.Value, 0))
{
string[] citations = Regex.Split((string)tranPart.Value, ";").Where(s => s != String.Empty).ToArray();
int citNumb = 1;
indexes.Add(tempProcessTrans.IndexOf(tran));
foreach (string singleCitation in citations)
{
addOn.Add(ChangeTrans(tran, singleCitation, citNumb++)); when this line runs changes occur to all lists as well as trans, tranPart
}
break;
}
}
}
foreach (int index in indexes.OrderByDescending(x => x))
{
processTrans.RemoveAt(index);
}
processTrans.AddRange(addOn);
return processTrans;
}
public static TransList ChangeTrans(TransList copyTransList, string singleCitation, int citNumb) //add ConFee
{
foreach (Transaction temp in copyTransList.OfType<TranID>())
{
temp.Value += "-" + citNumb;
}
foreach(Transaction temp in copyTransList.OfType<Comment2>())
{
temp.Value = singleCitation;
}
foreach (Transaction temp in copyTransList.OfType<Amount>())
{
//temp.Value = DboGrab(temp);
//temp.Value = amount;
}
return copyTransList;
}
public class Transaction : TranInterface
{
public string Name;
public object Value;
public string Formating;
public Transaction(string name, object value, string formating)
{
Name = name;
Value = value;
Formating = formating;
}
}
class TranID : Transaction
{
public TranID(string Name, string Value, string Formating) : base("Transaction ID", Value, "#") { }
}
public class TransList : IEnumerable<Transaction> //not to add all the lengthy parts here but this just allows for adding the parts and iterating through them in the foreach statements
{}
The behavior you're seeing is an inherent feature of reference types. When you call the ChangeTrans() method, the reference returned by that method is exactly the same as the one you passed in, which is that original value tran. Within the inner loop, the value of tran never changes, so on each iteration of the loop, you are modifying the same object over and over, adding it to your addOn list with each iteration.
This has two undesirable effects:
There is no difference between each element in the addOn list. They are all identical, referencing the same single object.
Any modification of any single element in the addOn list, or via the original reference to that single object, is visible via every other reference to that same single object. I.e. via all of the other elements in the list, and even that original reference in the tran variable (and of course, the copyTranList variable, which was assigned to the value of tran).
Without a more complete code example, it's not possible to know for sure what the best solution would be. However, one naïve solution would be to simply change your ChangeTrans() method so that it is responsible for making the new copy:
public static TransList ChangeTrans(
TransList copyTransList, string singleCitation, int citNumb) //add ConFee
{
TransList newTransList = new TransList();
foreach (Transaction temp in copyTransList.OfType<TranID>())
{
Transaction newTransaction = new TranID();
newTransaction.Value = temp.Value + "-" + citNumb;
newTransList.Add(newTransaction);
}
foreach(Transaction temp in copyTransList.OfType<Comment2>())
{
Transaction newTransaction = new Comment2();
newTransaction.Value = singleCitation;
newTransList.Add(newTransaction);
}
return newTransList;
}
Note: I have no idea if the above actually would compile, or if it actually copies all of the values needed. I reiterate: since you have not shown the TransList or Transaction data structures, it's not possible to know what all in them needs to be copied, nor what the best way to copy those values would be.
That said, note in the above example that this version of the method:
Creates an entirely new instance of the TransList object, storing the reference in newTransList.
For each Transaction value to be modified, it creates an entirely new instance of Transaction (using the appropriate type), assigning to that instance's Value property the modified value.
For each of those new Transaction objects, it adds the object to the newly-created TransList object referenced by the newTransList variable.
Finally, it returns that newly-created TransList object, rather than the one that was passed to the method.
Presumably you know what the correct way to add Transaction elements to TransList object, as well as whether there are other members in a Transaction object that would need to be copied. The above is simply a basic illustration of where and how you can modify your code so that you do the "deep copy" needed to avoid the problem you're describing.
I have a small problem with my Exchange Appointment. The idea is to sync a meeting from sharepoint calendar to the personal exchange calendar.
I have this StringList in my CalendarItem Class:
private StringList m_Category;
public StringList Category { get { return m_Category; } }
And there it should go:
Microsoft.Exchange.WebServices.Data.Appointment xApointment = new Appointment(m_Service)
xApointment.Categories = xItem.Category; //xItem = Instance of CalendarItem
In the Microsoft.Exchange.WebService.Data.Appointment I have the predefinied StingList Categories.
What happens now is that I'm parsing through an XML File which looks like:
<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema"
xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<rs:data ItemCount="1">
<z:row ows_ContentTypeId="0x010200C5A7325634A3154BB8249D1C36246E00"
ows_Title="Test GetAllViewFields"
ows_Location="Testhausen"
ows_EventDate="2014-12-15 08:00:00"
ows_EndDate="2014-12-15 09:00:00"
ows_Description="Ein Test meeting"
ows_fAllDayEvent="0"
ows_fRecurrence="0"
ows_EventType="0"
ows_RecurrenceID="2014-12-15 08:00:00"
ows_Duration="3600"
ows_ParticipantsPicker=""
***ows_Category="Geschäftlich"***
And than I'm parsing this whole XML Code as a String and check if the name is there:
private void initFromXmlAttribute(System.Xml.Linq.XAttribute x)
{
string AttributeName = x.Name.LocalName.Replace("ows_", "");
try
{
if
(AttributeName == "Category")
{
m_Category= x.Value; //Error implicite convert not possible StringList to String
return;
}
The Error is because m_Category = StringList and x.Value = String.
Does anyone has an idea how to solve this little issue?
I am not familiar with class StringList, but I guess it a Collection.
You can simply initialize a new StringList with the string inside it :
m_Category = new StringList() { x.Value };
Assuming you are asking about this class, you'll see that its constructor accepts an IEnumerable<string>, so you can write:
m_Category=new StringList(new[]{x.Value});
StringList implements IEnumerable so you can also use the collection initializer syntax:
m_Category=new StringList{x.Value};
This creates the class in two steps - first creates an empty object and then calls Add for each item in the initializer
You should be able to create a new Stringlist with the desired values (StringList inherits from List(Of String), so it's quite straightforward:
myStringList = new StringList()
myStringList.add(x.Value)
Btw since you are effectively setting your "Category" Property you might want to consider including a "set" statement to your property instead of modifying your private variable directly. In fact you can skip defining your private variable completely by using:
public StringList Category { get; set; }
Category = new StringList()
The compiler will do the rest for you.