Using ToList() when copying Lists [duplicate] - c#

This question already has an answer here:
Entity Framework, get list for database first case
(1 answer)
Closed 5 years ago.
I have a program in C# (Visual Studio) and part of the code looks like this:
Class 1:
private void part_TextChanged(object sender, EventArgs e)
{
List<string> parameters = part.selectedParameters;
// Lots of code
List<string> allParameters = parameters.ToList();
for (int k = 0; k < limit; k++)
{
allParameters.Add("text");
}
}
Class 2:
public bool DoAnalysis()
{
List<string> partParameters = part.selectedParameters;
// Lots of code
List<string> allPartParameters = partParameters;
for (int k = 0; k < limit; k++)
{
allPartParameters.Add("text");
}
}
My question is concerning the use of ToList(). I want to copy List1 to List2 and working with List2 without List1 being changed too. Applying this to my code, I used .ToList() to deal with this. Adding ToList() was not a problem in Class 1 --> parameters.ToList() but when I want to add it in Class 2 to List<string> allPartParameters = partParameters, it is not possible. I only get the options ToArray() and ToString().
So, why can I add ToList() to a List in one part of the code and not in the other? Am I missing some property dependency somewhere else in the code?

Usually with dependency problems you can right click the red highlighted code and choose "Quick Actions and Refactoring" then a list will come up of dependencies you can possibly use. This will save you time typing it and has helped me tons.

Related

Matching lisboxes items and creating result

I am creating an Exam system in c#. I am creating result, i have answers in a listbox1 and correct answers in another listbox2, my issue is values in the listboxes should be compared and result should be generated on its base. If half the values match student is pass otherwise fail.
My code for this is following but it does not work.
for(int intCount = 0; intCount < listBoxSanswers.Items.Count;intCount++)
{
for (int intSubCount = 0; intSubCount < listBoxActAnswers.Items.Count; intSubCount++)
{
if (listBoxActAnswers.Items[intCount].ToString() == listBoxActAnswers.Items[intSubCount].ToString())
{
listBox3.Items.Add(listBoxActAnswers.Items[intCount].ToString());
}
}
}
If you want to use your approach, than you have to change one of the two lists to listBoxSanswers
If you want a shorter way, without the loops, you can try this line:
listBox3.Items.AddRange(listBoxActAnswers.Items.Cast<string>().ToList().Intersect(listBoxSanswers.Items.Cast<string>().ToList()).ToArray());
EDIT:
Oh okay, so you have a DataTable as a DataSource.
Than you can do it this way:
listBox3.Items.AddRange(listBoxActAnswers.Items.Cast<DataRowView>().Select(r => r[0]).ToList().Intersect(listBoxSanswers.Items.Cast<DataRowView>().Select(r => r[0]).ToList()).ToArray());
Maybe you should adapt Select(r => r[0]) to the right column which is your DisplayMember.

Adding to array C# [closed]

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 5 years ago.
Improve this question
I have the following : var navitems = new Button[5] .. Now how do I add to the array? I keep getting a null reference at runtime. To add, i am doing the following in a for loop :
for(int i=0;i<6;i++)
{
button b=new Button();
navitems[i]=b;
}
Note : No need to worry about how the buttons will be formatted, I already have that covered.
Fine here is the actual code, didn't wanna give too much away..
var groups = Connection.Groups();
var navitems = new TileNavItem[5];
for (int i=0;i > groups.Count; i++)
{
TileNavItem item = new TileNavItem()
{
Caption = groups[i].Description,
TileText = "Dashboards"
};
navitems[i] = item;
}
I'm using devexpress trial and i would like to create my tilenavpane items dynamically.. If i do the following navitems.Items.AddRange(new TileNavItem[] { item1, item2, item3 });, it works great so I figured I could easily implement this dynamically.
You should define your array the correct size for your items, and be more careful with your for-loops:
var groups = Connection.Groups();
var navitems = new TileNavItem[groups.Count];
for (int i=0; i < groups.Count; i++)
{
navitems[i] = new TileNavItem
{
Caption = groups[i].Description,
TileText = "Dashboards
};
}
Note that I also removed a superfluous variable.
This code may still fail if Connection.Groups can return null items.
You need increase array size
var navitems = new Button[6]
of decrease loop
for(int i=0;i<5;i++)
{
button b=new Button();
navitems[i]=b;
}
You can add TileNavItem(s) to the collection at run time after adding the initial 5 (not tested):
TileNavItem item6 = new TileNavItem() { TileText = "Item 6" };
navitems.Items.Add(item6);
https://documentation.devexpress.com/WindowsForms/18127/Controls-and-Libraries/Navigation-Controls/TileNav-Pane/How-to-Create-and-Customize-the-TileNavPane-Control-in-Code

c# collections and re-numbering not working as expected

Hi i'm trying to setup simple test data.
I simply want to take a collection which is smallish and make it bigger by add itself multiple times.
After I;ve added them together i want to re-number the property LineNumber
so that there are no duplicates and that it goes in order. 1,2,3,4....
no matter what i try it doesn't seem to work and i cant see the mistake.
var sampleTemplateLine = dataContext.TemplateFileLines.ToList();
*//tired this doesnt work either*
//List<TemplateFileLine> lineRange = new List<TemplateFileLine>();
//lineRange.AddRange(sampleTemplateLine);
//lineRange.AddRange(sampleTemplateLine);
//lineRange.AddRange(sampleTemplateLine);
//lineRange.AddRange(sampleTemplateLine);
var allProducts = sampleTemplateLine
.Concat(sampleTemplateLine)
.Concat(sampleTemplateLine)
.Concat(sampleTemplateLine)
.ToList();
int i = 1;
foreach (var item in allProducts)
{
item.LineNumber = i;
i++;
}
this doesnt seem to work either
//re-number the line number
var total = allProducts.Count();
for (int i =0; i < total; i++)
{
allProducts[i].LineNumber = i+1;
}
PROBLEM: below RETURN 4 when i'm expecting 1
var itemthing = allProducts.Where(x => x.LineNumber == 17312).ToList();
You are adding the same objects multiple times. You wold have to add new objects or clone the ones you have.
The problem is they are pointing the same object. So if you change a property it changes all the pointed objects at the same
You can use Clone method if it exist, if not you can create your own Clone method like in this question.

C# How to programmatically build property name [duplicate]

This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 7 years ago.
I have an object called "Agent". Agent has among others, 10 properties named lab1 thru lab10. I need to assign these properties to text boxes on a form txtFieldLabel1 thru txtFieldLabel10. In the example below the left side of the operator in the loop is fine. I can't figure out the right side. I need to dynamically build the property name based on the index of the loop. This seems it should be fairly simple and similar to the left side of the operator.
for (int i = 1; i <= 10; i++)
{
tlp.Controls["txtFieldLabel" + i.ToString()].Text = Agent.lab + i.ToString();
}
Agent.GetType().GetProperty("lab" + i).GetValue(Agent, null);
That will get the value of the property that, using reflection, is defined as labX, where X is the value of i.
Edit: changed to GetValue(Agent, null) instead of GetValue(Agent), as the overload for the single object parameter was introduced in .NET 4.5.
You could use reflection as others mentioned, but it would be easier if you created Dictionary<int, string> inside your Agent class and define those KeyValuePairs with keys from 1 to 10 and desirable values corresponding to those keys. Here is an example:
public class Agent
{
public Dictionary<int, string> Lab = new Dictionary<int, string>();
public Agent()
{
this.Lab.Add(1, "Value 1");
this.Lab.Add(2, "Value 2");
this.Lab.Add(3, "Value 3");
// ...
this.Lab.Add(10, "Value 10");
}
}
Then you could call it like this:
var agent = new Agent();
for (int i = 1; i <= 10; i++)
tlp.Controls["txtFieldLabel" + i].Text = agent.Lab[i];
This seems it should be fairly simple and similar to the left side of the operator.
It's not simple at all; you can do it using reflection, but that's pretty advanced programming.
I suspect there are more meaningful property names available to you than lab1, lab2, etc. and strongly recommend you use them. Anyone who has to come back to this code in a few months will be grateful.
You can get the properties' values using reflection:
var agent = new Agent();
//...
var value = agent.GetType().GetProperty("lab" + i).GetValue(agent);
(Note: Agent is the class-name, while agent is the variable/instance)
Another (better/cleaner?) solution might be to implement the lab-properties as an array or List<string>, e.g:
class Agent {
public List<string> Labs {get;set;}
}
Then you could iterate over all Labs:
for (var i=0; i<agent.Labs.Count; i++) {
tlp.Controls["txtFieldLabel" + (i+1)].Text =
agent.Labs[i];
}

Instantiating object in a for loop base on index [duplicate]

This question already has answers here:
How to create variables with dynamic names in C#?
(6 answers)
Closed 8 years ago.
I'm trying to do something I 'm not even sure it's possible , therefore I would like to seek some suggestions.
I want to create 20 objects and each object names is assigned according to their number given. All twenty objects will be instantiated from the class called myClass, and they will have name called object_0,object_1,object_2 and so on.. with the properties i defined in the class given below. Is that possible?? Thanks
Let say i want to implement these codes, click is just like a Main void to trigger these codes
private void button_Click(object sender, EventArgs e)
{
for (int i = 0; i < 20; i ++)
{
myClass object_i = new myClass();
}
}
public class myClass
{
public myClass
{
}
}
I dont know what you are trying to do exactly, but use a List to store your object.
var myListOfObjects = new List<MyClass>();
for (var i = 0; i < 20; i++)
{
myListOfObjects.Add(new MyClass());
}
And if you look # your code ... your crteated objects lifetime is only inside the Loop :)
Referencing to the comment of #Alex-k you also could use a Dictionary if you want to store the objects by key
var myDictOfObjects = new Dictionary<string, MyClass>();
for (var i = 0; i < 20; i++)
{
myDictOfObjects.Add(string.Format("object_{0}", i), new MyClass());
}

Categories