List of all uncommon elements in arraylist - asp.net

I have 2 ArrayList, which contains the filenames, now one list has more names and other might have less, or sometime equal, i want to list the filenames which are not common in both arraylist and accordingly update the database, i was able to check whether they are equal or not, but i am unable to list which list has extra elements and which are they.
Here is a code which i am currently using.
ArrayList DatabaseSavedThumbnail = objSlideShow.GetAllThumbnailBySlideShowId();
string[] FolderSavedThumbnail = Directory.GetFiles(Server.MapPath("~/Portals/2/SlideShowThumbnails/" + SlideShowName));
if (Directory.GetFiles(Server.MapPath("~/Portals/2/SlideShowThumbnails/" + SlideShowName)).Length > 0)
{
if (!Object.Equals(DatabaseSavedThumbnail, FolderSavedThumbnail))
{
for (int i = 0; i < DatabaseSavedThumbnail.Count && i < FolderSavedThumbnail.Length; i++)
{
if (!object.Equals(DatabaseSavedThumbnail[i], FolderSavedThumbnail[i]))
{
if (DatabaseSavedThumbnail.Count > FolderSavedThumbnail.Length)
{
objSlideShow.Thumbnail = "/Portals/2/SlideShowThumbnails/" + SlideShowName + "/" + Path.GetFileName(DatabaseSavedThumbnail[i].ToString());
}
else
{
objSlideShow.Thumbnail = "/Portals/2/SlideShowThumbnails/" + SlideShowName + "/" + Path.GetFileName(FolderSavedThumbnail[i].ToString());
}
}
Response.Write(objSlideShow.Thumbnail + "<br>");
/*objSlideShow.SlideTitle = String.Empty;
objSlideShow.SlideDescription = string.Empty;
objSlideShow.AddSlide();*/
}
}
}
But this list all the elements of the arraylist which has more elements, i just want the differential elements, so that i can update the database with those elements only.
Can anyone tell me how could i get the differential records comparing 2 array list.

Try this to get elements not common in both lists (assuming DatabaseSavedThumbnail has strings):
using System.Linq;
...
...
var dstArray = DatabaseSavedThumbnail.ToArray(typeof(string));
var fstArray = FolderSavedThumbnail;
var notCommonElements = dstArray.Union(fstArray).Except(dstArray.InterSect(fstArray));
A very naive iterative approach can be:
private IEnumerable<string> GetNotCommonElements(string[] array1, string[] array2)
{
foreach (var item in array1)
{
if (!array2.Contains(item))
{
yield return item;
}
}
foreach (var item in array2)
{
if (!array1.Contains(item))
{
yield return item;
}
}
}
Then use it like:
foreach(var item in GetNotCommonElements(dstArray, fstArray))
{
// Do stuff with item
}

you can get idea from this
List<int> intersection = first.Cast<int>().Intersect(second.Cast<int>()).ToList();
or
ArrayList intersection = new ArrayList();
foreach (var i in first.Cast<int>().Intersect(second.Cast<int>()))
intersection.Add(i);
More detail
Two ArrayList manipulation

Related

How can i get columns added on column?

heres my code below...
TableColumn tc = new TableColumn();
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}
and i try to override commit method for editing cells.
public void commit(Object val) {
// Get the table
TableView<MainTable> t = this.getTableView();
// Get the selected row/column
MainTable selectedRow = t.getItems().get(this.getTableRow().getIndex());
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
// Get current property name
String propertyName = ((PropertyValueFactory) selectedColumn.getCellValueFactory()).getProperty();
// Create a method name conforming to java standards ( setProperty )
propertyName = ("" + propertyName.charAt(0)).toUpperCase() + propertyName.substring(1);
// Try to run the update
try {
// Type specific checks - could be done inside each setProperty() method
if(val instanceof Double) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, double.class);
method.invoke(selectedRow, (double) val);
}
if(val instanceof String) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, String.class);
method.invoke(selectedRow, (String) val);
}
if(val instanceof Integer) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, int.class);
method.invoke(selectedRow, (int) val);
}
} catch (Exception e) {
e.printStackTrace();
}
// CommitEdit for good luck
commitEdit((String) val);
}
and i got ArrayIndexOutofBoundsException on console view.
so my question is
how can i select getcolumns added other column???
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
i think this code has to be changed...
anyone got ideas??
Nested columns are not part of the TableView.columns list.
If you need the corresponding TableView column, just go up through the hierarchy until you reach a column without a parentColumn:
TableColumn<MainTable, ?> selectedColumn = this.getTableColumn();
TableColumn<MainTable, ?> c = selectedColumn;
while ((c = selectedColumn.getParentColumn()) != null) {
selectedColumn = c;
}
If you just need the column itself, simply use this.getTableColumn(), instead of finding the index of the column in the columns list and then accessing that index in the same list. (I guess the latter is what you need.)
Furthermore, if PropertyValueFactory returns properties of the item class, you could use this property to set the value instead of using reflection:
ObservableValue obs = selectedColumn.getCellObservableValue(this.getIndex());
if (obs instanceof WritableValue) {
((WritableValue) obs).setValue(val);
} else {
// reflecitive approach
}
Furthermore you shouldn't add null as a nested column, but you're doing it here:
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}

How to check for a specific value in List<T> foreach loop

Need help checking for a specific value in List<T> foreach loop. If there is specific value then display a specific string value.
For example how do I…
If (value.something_2 == "Null")
{
value.something_2 == ".";
}
Elseif (value.something_2 == " ")
{
value.something_2 == "0";
}
How would I incorporate the above example within the “foreach” loop?
See code below.
protected void MyReport(string filename, IMyRepository repository)
{
using (FileStream fileStream = new FileStream(Server.MapPath(#"~/Includes/") + filename, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
List<Report> _report = repository.GetMyReport().ToList();
foreach (var value in _report)
{
String row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_1,
values.something_2,
value.something_3);
String row02 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_4,
values.something_5,
value.something_6);
Writer.WriteLine(row01);
Writer.WriteLine(row02);
}
}
writer.Close();
}
}
There is no clever built-in String.Format that you can do for this if that's what you have in mind. However, the compiler has some tricks that can reduce the amount of code you need to write e.g.
// if it's null, assign it to "."
var s2 = value.something_2 ?? ".";
// it can never be null here, so if there is whitespace default to "0"
value.something_2 = String.IsNullOrWhitespace(s2) ? "0" : s2;
If I'm understanding what you're saying, it might be easier just to have another function returning the (possibly) modified string and just pass each of your values into it, inline.
Sting row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", myFunc(value.somthing_1), myFunc(values.something_2), myFunc(value.something_3));
and then have this in the same class
private string myFunc(string something){
if (something == “Null”){
return “.“;
} else if (something == “ “) {
return “0”;
} else {
return something;
}
}

how to set datarow to String array?

I have a datatable on which I am applying Select() method. After that I want to get the result into an array of String. I have tried the following code but it is not working.
Please let me know the exact solutions for this.
DataTable dtget = HttpContext.Current.Cache["Hello"] as DataTable;
string sqlFilter = "Securityid = '" + CommonClass.Encryptdata(txtSecurity.Text) + "'";
DataRow[] dr = dtget.Select(sqlFilter);
if (dr.Length > 0)
{
String[] Con;
for (int i = 0; i <= dr.Length; i++)
{
dr[i] = dr[i].ToString();
}
}
You have to create the List<T>.
Something like this:
List<String[]> list=new List<String[]>();
if (dr.Length > 0)
{
for (int i = 0; i < dr.Length; i++)
{
string []ar=new string[dtget.Columns.Count];
for(int j=0;j<dtget.Columns.Count;j++)
{
ar[j]=dr[i][j].ToString();
}
list.Add(ar);
}
}
You've declared the array, but not instantiated it. and you're also not writing anything to the actual array, you're trying to write straight back to the datatable.
String[] Con= new String[dtget.Columns.Count];
for (int i = 0; i <= dr.Length; i++)
{
Con[i] = dr[i].ToString();
}
The problem is that you are assigning values to the datarrow in stead of to your string array.
Change
dr[i] = dr[i].ToString();
to
con[i] = dr[i].ToString();
also you are missing the new statement for Con:
Con = new String[dr.Table.Columns.Count];
notice that there is no such thing as dr.Length, you have to check for the column count:
dr.Table.Columns.Count
lastly, you should probably move the string array definition up so it's available outside the IF.
Depending on your needs, what you could do is use the Datarow's ItemArray property. It is an object array in stead of a string array, but before using it's values you can do a "ToString()" and you are all set.
string a = dr.ItemArray[i].ToString();

How to append new list item to a list

I would like to find a list paragraph (starting with a. ), and append another list item to this list (it depend on the text of first list element).
I have tried many ways of creating new paragraph, but all what I achieved is that new list elements are created, but org.docx4j.wml.Text objects are appended to paragraph the new paragraph was appended. The new paragraph text is empty. How can be new list element created and appended to the right element?
a. list element 1 |test| //|test| should be appended to b.
b. //new items are created, but there is no text
c.
//traverse through a document
public List<Object> apply(Object obj) {
if (obj instanceof org.docx4j.wml.P) {
if (p.getPPr() != null) {
if (p.getPPr().getPStyle() != null) {
if ((p.getPPr().getPStyle().getVal().equals("Akapitzlist"))) {
//there is a list paragraph
ObjectFactory factory = Context.getWmlObjectFactory();
Object deepCopy = XmlUtils.deepCopy(obj);
//Create the paragraph
org.docx4j.wml.P para = factory.createP();
// Create the text element
org.docx4j.wml.Text t = factory.createText();
t.setValue("|test|");
// Create the run
org.docx4j.wml.R run = factory.createR();
run.getContent().add(t);
para.getContent().add(run);
//add new paragraph to the document
((org.docx4j.wml.P) obj).getContent().add(para);
}...}
My solution, just append to the body with incremented index. I' am creating deep copy to preserwe style.
public List<Object> apply(Object obj) {
Object deepCopy = null;
if (obj instanceof org.docx4j.wml.P) {
org.docx4j.wml.P p = (org.docx4j.wml.P) obj;
if (p.getPPr() != null) {
if (p.getPPr().getPStyle() != null) {
if ((p.getPPr().getPStyle().getVal().equals("Akapitzlist")) && (akapListCounter < 10)) {
if (((org.docx4j.wml.P) obj).getPPr().getPStyle() != null) {
if ((((org.docx4j.wml.P) obj).getPPr().getPStyle().getVal().equals("Akapitzlist"))) {
deepCopy = XmlUtils.deepCopy(obj);
akapListCounter++;
int indexOf = wmlDocumentEl.getBody().getContent().indexOf(obj);
List<Object> content = ((org.docx4j.wml.P) deepCopy).getContent();
for (Object el : content) {
System.out.println("class1:" + el.getClass().toString());
if (el instanceof org.docx4j.wml.R) {
List<Object> subc = ((org.docx4j.wml.R) el).getContent();
for (Object r : subc) {
((javax.xml.bind.JAXBElement) r).setValue("tetetete");
}
}
}// end for
wmlDocumentEl.getBody().getContent().add(indexOf + 1, deepCopy);
}
}//end get style
}
}
} else {}
}
return null;
}

Create HTML table out of object array in Javascript

I am calling a web Method from javascript. The web method returns an array of customers from the northwind database. The example I am working from is here: Calling Web Services with ASP.NET AJAX
I dont know how to write this javascript method: CreateCustomersTable
This would create the html table to display the data being returned. Any help would be appreciated.
My javascript
function GetCustomerByCountry() {
var country = $get("txtCountry").value;
AjaxWebService.GetCustomersByCountry(country, OnWSRequestComplete, OnWSRequestFailed);
}
function OnWSRequestComplete(results) {
if (results != null) {
CreateCustomersTable(results);
//GetMap(results);
}
}
function CreateCustomersTable(result) {
alert(result);
if (document.all) //Filter for IE DOM since other browsers are limited
{
// How do I do this?
}
}
else {
$get("divOutput").innerHTML = "RSS only available in IE5+"; }
}
My web Method
[WebMethod]
public Customer[] GetCustomersByCountry(string country)
{
NorthwindDALTableAdapters.CustomersTableAdapter adap =
new NorthwindDALTableAdapters.CustomersTableAdapter();
NorthwindDAL.CustomersDataTable dt = adap.GetCustomersByCountry(country);
if (dt.Rows.Count <= 0)
{
return null;
}
Customer[] customers = new Customer[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
NorthwindDAL.CustomersRow row = (NorthwindDAL.CustomersRow)dt.Rows[i];
customers[i] = new Customer();
customers[i].CustomerId = row.CustomerID;
customers[i].Name = row.ContactName;
}
return customers;
}
Try to look what is the result variable value in debug mode. If the structure seems the structure that i'm imagining, something like this could work:
function CreateCustomersTable(result) {
var str = '<table>';
str += '<tr><th>Id</th><th>Name</th></tr>';
for ( var i=0; i< result.length; i++){
str += '<tr><td>' + result[i].CustomerId + '</td><td>' + result[i].Name + '</td></tr>';
}
str += '</table>';
return str;
}
And then You can do somethig like this:
var existingDiv = document.getElementById('Id of an existing Div');
existingDiv.innerHTML = CreateCustomersTable(result);
I wish this help you.
Something like this, assuming you have JSON returned in the "result" value. The "container" is a div with id of "container". I'm cloning nodes to save memory, but also if you wanted to assign some base classes to the "base" elements.
var table = document.createElement('table');
var baseRow = document.createElement('tr');
var baseCell = document.createElement('td');
var container = document.getElementById('container');
for(var i = 0; i < results.length; i++){
//Create a new row
var myRow = baseRow.cloneNode(false);
//Create a new cell, you could loop this for multiple cells
var myCell = baseCell.cloneNode(false);
myCell.innerHTML = result.value;
//Append new cell
myRow.appendChild(myCell);
//Append new row
table.appendChild(myRow);
}
container.appendChild(table);
You should pass the array as JSON or XML instead of just the toString() value of it (unless that offcourse is returns either JSON oR XML). Note that JSOn is better for javascript since it is a javascript native format.
Also the person who told you that browser other then IE can not do DOM manipulation should propably have done horrible things to him/her.
If your format is JSON you can just for-loop them and create the elements and print them. (once you figured out what format your service returns we can help you better.)

Resources