List<myJavaClass> smallListnew = (List<myJavaClass>) i1.next();
Above line causing error says object can not be type casted to type List<myJavaClass>.
Below is some description code:
List<myJavaClass> i1=bigList.iterator();
Big list contains many small list in the following way:
//here unique list contains some Long values without the duplicates that were being compared with the refreshJobCountList.
Iterator<Long> i=uniqueRefJobId.iterator();
while (i.hasNext()) {
Long refreshJobID = i.next();
List<myJavaClass> smallList = new ArrayList<>();
for (myJavaClass details : refreshJobCountList) {
if (refreshJobID.equals(details.getRefreshJobId())) {
myJavaClass new_obj=new myJavaClass();
new_obj.setCount(details.getCount());
new_obj.setJobRunId(details.getJobRunId());
new_obj.setRefreshJobId(details.getRefreshJobId());
smallList.add(new_obj);
}
}
bigList.addAll(smallList);
}
Instead of typecasting the array. Add the elements of the small list to a bigger list. Use .allAll() to add the entire list.
Related
Using visual studio here. In code below you can see a string being a split, and I want put each split string in a new row, but program crashes not creating a new row and I got error:
Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
String^ text = textBox1->Text;
cli::array<String^>^ part = text->Split('.','?','!');
for (int split = 0; split < part->Length; ++split)
{
datagrid->Rows[split]->Cells[3]->Value = part[split];
}
You probably don't have enough rows in you data grid so you'll need to add them inside your loop:
String^ text = textBox1->Text;
cli::array<String^>^ part = text->Split('.','?','!');
datagrid->Rows->Clear();
for (int split = 0; split < part->Length; ++split)
{
datagrid->Rows->Add(part[split]);
}
I currently am populating a dropdown list with the contents of all files in a directory using this code:
string[] filePaths = Directory.GetFiles(#ConfigurationManager.AppSettings["File_Path"]
.ToString(), "*.txt");
if (filePaths == null || filePaths.Length == 0)
{
ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
ddlFiles.DataSource = filePaths;
ddlFiles.DataBind();
ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}
The problem is that the dropdown will show the complete path to the files. I just want to show the file name and extension. I figure that I could use a two dimensional List, and load the path into one dimension. I could then just loop through that dimension and parse everything after the last "\" to get just the file name and write it back to the other dimension in that List. This would result in a List with two dimensions, one with paths and one with file names. I could then load the dropdown from the 2 dimensional List using the path for the DataValueField and the file name for the DataTextField.
My problem is that I can't get a 2 Dimensional List to load from Directory.GetFiles. Can someone post an example?
Also, how do I specifically address each dimension in the List to load the Value/Text attributes of the dropdown list?
Thank You in advance for your help!
I don't think you need multi-dimensional arrays here.. You can just separate "Value" and "Text". That is, data binding supports value and text, using "DataValueField" and "DataTextField", you could just use those. Means, first you get a list of pairs, and then bind them to the value/text of the item, like this:
var filePaths = Directory.GetFiles(#ConfigurationManager.AppSettings["File_Path"].ToString(), "*.txt")
.Select(path => new
{
Path = path,
Name = Path.GetFileName(path)
}).ToArray();
if (filePaths == null || filePaths.Length == 0)
{
ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
ddlFiles.DataSource = filePaths;
ddlFiles.DataValueField = "Path";
ddlFiles.DataTextField = "Name";
ddlFiles.DataBind();
ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}
I have 2 List one stores the name of filterable columns(of type DropDown) and another store the values to load in those filterable columns.
List<string> filterableFields = new List<string>() { "A_B", "C_D", "E_F" };
List<string> AB, CD , EF;
Now at the run time I get the data from web service and I have written a function to to extract values for these filterable fields and store the values to 2nd List.
private void prepareListForFilterableColumns(XDocument records)
{
foreach (var currentField in filterableFields)
{
var values = (from xml in records.Descendants(z + "row")
let val = (string)xml.Attribute("ows_" + currentField.Replace("_", "_x0020_"))
where val != ""
orderby val
select val
).Distinct();
switch (currentField)
{
case "A_B": AB = values.ToList(); break;
case "C_D": CD = values.ToList(); break;
}
}
}
Now I was thinking that instead of hard coding the assignment in swtich case block, If I could just use the first List name "A_B" and replace "_" from it to point to my 2nd List and assign values.ToList() to it.
I understand that c# is a static language, So not sure if we can achieve this, but IF I can it will make my function generic.
Thanks a lot in advance for time and help.
Vishal
You could use a dictionary of lists of strings instead of 3 lists to store the values.
Dictionary<string, List<string>> val lists = new Dictionary<string,List<string>>();
And make the keys of the dictionary equal to the filterables: "AB", "CD",..
then, instead of AB you would use valLists["AB"] and could then reference reach list based on a string key.
The other option would be to use reflection but that would be slower and unnecessarily a bit more complicated.
I have a file to put in a multidimensional array. I have to put to [0] a date (long) and one of the dimensions must be incremented depending on the value of the second token.
Here's the code :
BufferedReader bufStatsFile = new BufferedReader(new FileReader(statsFile));
String line = null;
List<Long[]> stats = new ArrayList<Long[]>();
stats.add(new Long[11]);
int i = 0; // will be in a loop later
while((line = bufStatsFile.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line,";");
while(st.hasMoreTokens()) {
stats.get(i)[0] = Long.parseLong(st.nextToken());
stats.get(i)[Integer.parseInt(st.nextToken())]++; // Here is the problematic line.
}
}
bufStatsFile.close();
But the incrementation doesn't work. Maybe it is because of my array which is probably not correct, but I didn't found another proper way to do that.
Ok. I have found and it was, of course, stupid.
The problem was in my array declaration. I did it like that :
List<Long[]> stats = new ArrayList<Long[]>();
stats.add(new Long[11]);
And then, I tried to increment an Object and not a long number.
So now, I just do it like this :
List<long[]> stats = new ArrayList<>();
stats.add(new long[11]);
And it's perfectly working.
Check that the elements in your file are numbers from 0 to 10. Why are you having a List if you are only manipulating the row 0?
Which exception are your code throwing away?
When the first cell of an excel sheet to import using ExcelStorage.ExtractRecords is empty, the process fail. Ie. If the data starts at col 1, row 2, if the cell (2,1) has an empty value, the method fails.
Does anybody know how to work-around this? I've tried adding a FieldNullValue attribute to the mapping class with no luck.
Here is a sample project that show the code with problems
Hope somebody can help me or point in some direction.
Thank you!
It looks like you have stumbled upon an issue in FileHelpers.
What is happening is that the ExcelStorage.ExtractRecords method uses an empty cell check to see if it has reached the end of the sheet. This can be seen in the ExcelStorage.cs source code:
while (CellAsString(cRow, mStartColumn) != String.Empty)
{
try
{
recordNumber++;
Notify(mNotifyHandler, mProgressMode, recordNumber, -1);
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
catch (Exception ex)
{
// Code removed for this example
}
}
So if the start column of any row is empty then it assumes that the file is done.
Some options to get around this:
Don't put any empty cells in the first column position.
Don't use excel as your file format -- convert to CSV first.
See if you can get a patch from the developer or patch the source yourself.
The first two are workarounds (and not really good ones). The third option might be the best but what is the end of file condition? Probably an entire row that is empty would be a good enough check (but even that might not work in all cases all of the time).
Thanks to the help of Tuzo, I could figure out a way of working this around.
I added a method to ExcelStorage class to change the while end condition. Instead of looking at the first cell for empty value, I look at all cells in the current row to be empty. If that's the case, return false to the while. This is the change to the while part of ExtractRecords:
while (!IsEof(cRow, mStartColumn, RecordFieldCount))
instead of
while (CellAsString(cRow, mStartColumn) != String.Empty)
IsEof is a method to check the whole row to be empty:
private bool IsEof(int row, int startCol, int numberOfCols)
{
bool isEmpty = true;
string cellValue = string.Empty;
for (int i = startCol; i <= numberOfCols; i++)
{
cellValue = CellAsString(row, i);
if (cellValue != string.Empty)
{
isEmpty = false;
break;
}
}
return isEmpty;
}
Of course if the user leaves an empty row between two data rows the rows after that one will not be processed, but I think is a good thing to keep working on this.
Thanks
I needed to be able to skip blank lines, so I've added the following code to the FileHelpers library. I've taken Sebastian's IsEof code and renamed the method to IsRowEmpty and changed the loop in ExtractRecords from ...
while (CellAsString(cRow, mStartColumn) != String.Empty)
to ...
while (!IsRowEmpty(cRow, mStartColumn, RecordFieldCount) || !IsRowEmpty(cRow+1, mStartColumn, RecordFieldCount))
I then changed this ...
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
to this ...
bool addRow = true;
if (Attribute.GetCustomAttribute(RecordType, typeof(IgnoreEmptyLinesAttribute)) != null && IsRowEmpty(cRow, mStartColumn, RecordFieldCount))
{
addRow = false;
}
if (addRow)
{
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
What this gives me is the ability to skip single empty rows. The file will be read until two successive empty rows are found