How to make every object in list null [closed] - c#

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 and I have populated it with myObjects. I do processing with the the objects and then I would like to have the objects garbage collected by releasing references to the objects. How would this be best acheived?
I can't use foreach loop because you can't alter the collection within the loop.

This updates the list, and doesn't create a new list with new contents.
for (i = 0; i < list.Count; i++) {
list[i] = null;
}

You basically want to iterate through the list, and assign each object to null, like so:
var myList = new List<object>();
for (var i = 0; i < 9; i++)
{
myList.Add(new object());
}
for (var i = 0; i < myList.Count; i++)
{
myList[i] = null;
}

Use the List(T).Clear() method: http://msdn.microsoft.com/en-us/library/dwb5h52a.aspx
This dereferences all objects and sets Count to 0.
If you really need to keep the same count and set each item in your list to null, you can simply use ForEach():
list.ForEach(x => x = null)

Related

Compare DB Item with an List<string> Input [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 4 years ago.
Improve this question
This is the data from my input
{Test,Sample}
This is the data from my database
{C:\Users\Test,D:\DriveB\Sample\Test,C:\Users\Private\Item\LocationB}
My expected output is
{C:\Users\Test,D:\DriveB\Sample\Test}
How can I get results out using that input? So far I have tried using a for loop like this
var Count = Input.Count;
for(var i = 0; i < Count; i++)
{
data = data.Where(u => u.Location.Contains(Input[i])).ToList();
}
The variable data has already been extracted from the database and has a format like this
Id
Name
Location
FileType
But the problem is that when it goes past the first loop, it immediately eliminates the second inputs data.
var Count = Input.Count;
data = data.Where(x => input.Any(y => x.Location.Contains(y))).ToList();
}
would likely work. The use of Any means:
Get me any row from data where at least one of the entries from input is contained in (i.e. a substring of) the Location.
Use split by "," first
var input = new List<String>() { "Test", "Sample" };
var db = #"C:\Users\Test,D:\DriveB\Sample\Test,C:\Users\Private\Item\LocationB";
var result = db.Split(',').Where(p => input.Any(c => p.Contains(c))).ToList();

Possible way to do to with foreach instead of for [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 4 years ago.
Improve this question
I am trying to convert DataGridView columns into an ArrayList. I would like to make this code into a foreach version. I tried to follow this answer but, it doesn't worked for me. With this for method my problem is, when I am deleting a bunch of rows from the datagridview, then it gives an error or my binary search doesn't work well. That's why I want to try with foreach method.
for (int i = 0 ; i < dataGridView2.Rows.Count; i++)
{
ListOfPeople[i] = dataGridView2.Rows[i].Cells[0].Value.ToString().Trim();
}
As an alternative to loops you can try query dataGridView2.Rows with a help of Linq and build ListOfPeople in one go:
// ArrayList is an obsolete class; let's use List<string>
List<string> ListOfPeople = dataGridView2
.Rows
.OfType<DataGridViewRow>()
.Select(row => row.Cells[0].Value.ToString().Trim())
.ToList();
Why can't you use foreach likewise for any other collection
foreach (DataGridViewRow row in dataGridView2.Rows)
{ // code here
}
The problem with the conversion of for to foreach is what to do with loop index i. Two situations are possible - when you need i, and when you don't need i.
When i is necessary, use Select that passes the index to you, like this:
foreach (var p in dataGridView2.Rows.Select((r, i) => new {Row = (DataGridViewRow)r, Index = i}) {
ListOfPeople[p.Index] = p.Row.Cells[0].Value.ToString().Trim();
}
When i is not necessary, you can use "straight" foreach, or even drop the loop altogether:
ListOfPeople = dataGridView2.Rows.Cast<DataGridViewRow>()
.Select(r => r.Cells[0].Value.ToString().Trim())
.ToList();
The old-school answer to your question (how to use a foreach instead of for) is pretty close to what #Rahul describes. However, the Rows collection was a pre-generic collection (i.e., it's been there since .NET v1.x), and when you foreach over it, you get objects, and not rows. Instead, this works:
foreach (var row in dataGridView2.Rows.Cast<DataGridViewRow>())
{ // code here
}
The old school way of keeping track of an index variable (i) is something like:
var i = 0;
foreach (var row in dataGridView2.Rows.Cast<DataGridViewRow>())
{
// your code here
++i;
}

Generate unique name for multiple worksheets in a for loop [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 4 years ago.
Improve this question
I am using for loop to generate some worksheets, and I want to give each one a unique name. All I get is Sheet1, Sheet2, Sheet3, and so on.
Below is my code:
var package = new ExcelPackage();
for (var i = 0; i < ds.Tables.Count; i++)
{
var ws = package.Workbook.Worksheets.Add(String.Format("Sheet{0}", i));
ws.Cells["A1"].LoadFromDataTable(i == 0
? Transpose(ds.Tables[i].Copy()).DefaultView.ToTable()
: ds.Tables[i], true, TableStyles.Medium1);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
ws.Cells["A:J"].Style.Numberformat.Format = "#,##0";
}
You haven't shown where the names are coming from, but probably the best way would be to use the name from some field in the same data source that you're using to populate the sheet.
Here's one one way to give them each unique names would be to have them stored in a list, which you can access using the same index that you're using currently. Of course you have to somehow ensure that the names are in the correct order in your list:
var sheetNames = new List<string> { "Summary", "EmployeeData", "Benefits" };
for (var i = 0; i < ds.Tables.Count; i++)
{
// Choose a name from the list or use 'Sheet1, 2, 3' if we don't have enough names
var sheetName = i < sheetNames.Count
? sheetNames[i]
: String.Format("Sheet{0}", sheetNames.Count - i);
var ws = package.Workbook.Worksheets.Add(sheetName);
In this line of code here:
var ws = package.Workbook.Worksheets.Add(String.Format("Sheet{0}", i));
You're setting the worksheet name, that's why you end up with 'Sheet1', 'Sheet2', etc.
Changing that to something else, you get your worksheets named differently.
Now, I'm not sure, if your problem is where you can change the name or how you can do it, to make it unique. Depending on what you're aiming for, you could use Guid's.

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

Using ToList() when copying Lists [duplicate]

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.

Categories