|
Hello everyone,
I have an Array which holds list of items. Some of the items in the list are repeated (Undesirable).
Can someone tell me how I can remove/rearange/rebuilt the array without the repeated items?
Thank you very much and have a great weekend.
Khoramdin
|
|
|
|
|
Just off the top of my head... this seems good, it's O(n)
<font>public datatype[] UnduplicateArray(datatype[] startarray)
{
List<datatype> endarray = new List<datatype>();
foreach (datatype d in startarray)
if (!endarray.Contains(d))
endarray.Add(d);
return endarray.ToArray();
}
</datatype></datatype></font>
Last modified: 1hr 31mins after originally posted --
|
|
|
|
|
eggsovereasy wrote: this seems good, it's O(n)
Are you sure?
The List.Contains method loops throught each item in the collection looking for an existing item. That doesn't seem very good...
I would rather use a Dictionary, as that uses a hash table, which is much faster when looking for an existing item.
---
single minded; short sighted; long gone;
|
|
|
|
|
You are absolutely correct, I didn't consider what Contains() was doing, so its probably more like O(n^2).
|
|
|
|
|
I've got a .NET 2 generic library that does operations on any kind of list. I have a Distinct method in that library that returns only the unique elements in the list. It looks something like:
public static IEnumerable<T> Distinct<T>(IEnumerable<T> items)
{
Queue<T> distinct = new Queue<T>();
foreach (T element in items)
{
if (!distinct.Contains(element))
{
distinct.Enqueue(element);
}
}
return distinct;
}
Then you can use it like this:
string[] myStrings = { "hello", "world", "hello" };
IEnumerable<string> distinct = Distinct(myStrings);
|
|
|
|
|
This is more flexible than my example, but its the same logic. I would use this were I the OP.
|
|
|
|
|
Considering that you are taking in and returning IEnumerable<t>, wouldn't it be better to use yield return, instead of returning the distinct elements in one shot? That way, it fits in well with the "lazy" evaluation semantics of IEnumerable<t> (like when items actually enumerates over the contents of a file, for example). Something like
public static IEnumerable<T> Distinct<T>(IEnumerable<T> items)
{
Queue<T> distinct = new Queue<T>();
foreach (T element in items)
{
if (!distinct.Contains(element))
{
distinct.Enqueue(element);
yield return element;
}
}
}
If the caller stops with the first two distinct elements, for example, then this saves a lot of needless computation.
|
|
|
|
|
Yes, good catch, Senthil. I'm a big fan of yield return -- I'm surprised I didn't catch it myself. Thanks.
|
|
|
|
|
Hi,
I am getting weird error while trying to check whether this xml document is well form or not.
Error I am getting is only for the xml file who has external dtd defined. If xml file requires a schema or inline dtd... it works perfectly fine. I tested this xml file with Stylus Studio Xml Editor and it works perfectly fine and validates the MessageExternalDTD.xml file. In my case the error it says is "Could not find file 'C:\Documents and Settings\ronak.patel\Local Settings\Temp\message.dtd'. Even though dtd file is at the same location as the xml file is.
One thing i understand from this error during validating or checking wellformness xml file requires dtd or xsd files to be present at "C:\Documents and Settings\ronak.patel\Local Settings\Temp\" directory. If they are there and not in the same directory where xml file is still it would work, but not vice versa.
MessageExternalDTD.xml
<message>
<to>Dave
<from>Susan
<subject>Reminder
<text>Don't forget to buy milk on the way home!
message.dtd
Here is my Code...
XmlDocument xmlDocument = xmlData.xmlDocument;
//xmlDocument is already given to me..
MemoryStream mstream = new MemoryStream();
StreamWriter writer = new StreamWriter(mstream);
xmlDocument.Save(mstream);
mstream.Seek(0, SeekOrigin.Begin);
try
{
while (reader.Read())
{
}
}
catch (XmlException ex)
{
MessageBox("XML Error : " + ex.Message);
m_success = false;
}
catch (Exception exe)
{
MessageBox("Error : " + exe.Message);
m_success = false;
}
finally
{
if (!m_success)
{
MessageBox.Show("Not Well Form");
}
else
{
MessageBox.Show("Well Form");
}
m_success = true;
reader.close();
}
|
|
|
|
|
Hi,
Can any one give me example of site where i can use
WebClient.DownloadFile(url,localfile); with Credentials...supplied to Webclient
like this
NetworkCredential auth = new NetworkCredential(tbUsername.Text, tbpassword.Text);
client.Credentials = auth;
I tried with so many sites but still no luck. Basically i want to download file from a website which asks for user credentials which i can pass to WebClient object.
|
|
|
|
|
Hi,
I am doing Http Get and Post operation using WebClient class of System.Net.
Is there a way to block cookies while i am doing this operations?
|
|
|
|
|
Hi,
I have working code of above function in vc++. I need help to convert it to c#....Any one know how to achieve this in c# please help me out here.
The code i got is from this link....
http://www.codeproject.com/dll/Execute_DLL_Function.asp
bool GetDLLFileExports(char *szFileName, unsigned int *nNoOfExports, char **&pszFunctions)
{
HANDLE hFile;
HANDLE hFileMapping;
LPVOID lpFileBase;
PIMAGE_DOS_HEADER pImg_DOS_Header;
PIMAGE_NT_HEADERS pImg_NT_Header;
PIMAGE_EXPORT_DIRECTORY pImg_Export_Dir;
hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if(hFile == INVALID_HANDLE_VALUE)
return false;
hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if(hFileMapping == 0)
{
CloseHandle(hFile);
return false;
}
lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
if(lpFileBase == 0)
{
CloseHandle(hFileMapping);
CloseHandle(hFile);
return false;
}
pImg_DOS_Header = (PIMAGE_DOS_HEADER)lpFileBase;
pImg_NT_Header = (PIMAGE_NT_HEADERS)((LONG)pImg_DOS_Header + (LONG)pImg_DOS_Header->e_lfanew);
if(IsBadReadPtr(pImg_NT_Header, sizeof(IMAGE_NT_HEADERS))||pImg_NT_Header->Signature != IMAGE_NT_SIGNATURE)
{
UnmapViewOfFile(lpFileBase);
CloseHandle(hFileMapping);
CloseHandle(hFile);
return false;
}
pImg_Export_Dir = (PIMAGE_EXPORT_DIRECTORY)pImg_NT_Header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
if(!pImg_Export_Dir)
{
UnmapViewOfFile(lpFileBase);
CloseHandle(hFileMapping);
CloseHandle(hFile);
return false;
}
pImg_Export_Dir= (PIMAGE_EXPORT_DIRECTORY)ImageRvaToVa(pImg_NT_Header,pImg_DOS_Header, (DWORD)pImg_Export_Dir, 0);
DWORD **ppdwNames = (DWORD **)pImg_Export_Dir->AddressOfNames;
ppdwNames = (PDWORD*)ImageRvaToVa(pImg_NT_Header, pImg_DOS_Header, (DWORD)ppdwNames, 0);
if(!ppdwNames)
{
UnmapViewOfFile(lpFileBase);
CloseHandle(hFileMapping);
CloseHandle(hFile);
return false;
}
*nNoOfExports = pImg_Export_Dir->NumberOfNames;
pszFunctions = new char*[*nNoOfExports];
for(unsigned i=0; i < *nNoOfExports; i++)
{
char *szFunc=(PSTR)ImageRvaToVa(pImg_NT_Header, pImg_DOS_Header, (DWORD)*ppdwNames, 0);
pszFunctionsIdea = new char[strlen(szFunc)+1];
strcpy(pszFunctionsIdea,szFunc);
ppdwNames++;
}
UnmapViewOfFile(lpFileBase);
CloseHandle(hFileMapping);
CloseHandle(hFile);
return true;
};
|
|
|
|
|
I'm rewriting a project from C++(MFC) to C#, mostly to learn this new language. In that project I use CAsyncSocket to create a TCP connection with another peer in a network to send some notification messages or some very small amount of data or a requests.
I tried to find a similar easy way to implement an asynchronous TCP connection in C#, but most of them are not.
Is there any alternative to that in C#? Is there any component or namespace or class that can help me do it quickly?
// "Life is very short and is very fragile also." Yanni while (I'm_alive) { cout<<"I love programming."; }
|
|
|
|
|
System.Net.Socket namespace?
only two letters away from being an asset
|
|
|
|
|
Thanks Mark.
Mark Nischalke wrote: only two letters away from being an asset
// "Life is very short and is very fragile also." Yanni while (I'm_alive) { cout<<"I love programming."; }
|
|
|
|
|
System.Net.Sockets namespace is what you want if you still want to use sockets.
.NET has a nice abstraction over sockets called Remoting. With remoting, instead of sending bytes over the pipe, you connect to a .NET object on the other end and call functions on it like a regular object. If you're interesting in .NET remoting, check out the System.Runtime.Remoting namespace, as well as the System.Runtime.Remoting.dll in the .NET framework.
Finally, the new "cool" way of cross-process communication is WCF (Windows Communication Foundation). It's new in .NET 3 and provides a messaging-based, loosely-coupled, service architecture. There are articles here at CP as well as articles around the net on how to use WCF.
|
|
|
|
|
Judah Himango wrote: System.Net.Sockets namespace is what you want if you still want to use sockets.
Ireally prefer not to do it that way. It needs a lot of works, I think.
Remoting and WCF.
Thanks alot judah.
I'm going to check them right now.
// "Life is very short and is very fragile also." Yanni while (I'm_alive) { cout<<"I love programming."; }
|
|
|
|
|
Is there a way to use Socks4, Socks4a or Socks5 proxy types with WebProxy class.
I have downloaded a Proxy Server "ccproxy" from
http://www.youngzsoft.net/ccproxy/screenshot.htm
where i can use my code to download and upload files but it works only with Port 808 reserved for HTTP proxy in ccproxy server.
Http Get Code...
WebClient client = new WebClient();
if (tbpassword.Text != "" && tbUsername.Text != "")
{
NetworkCredential auth = new NetworkCredential(tbUsername.Text, tbpassword.Text);
client.Credentials = auth;
}
if (tbProxyAddress.Text != "" && tbProxyPort.Text != "")
{
WebProxy proxy = new WebProxy(tbProxyAddress.Text, Convert.ToInt32(tbProxyPort.Text));
if(tbProxyUsr.Text != "" && tbProxyPwd.Text != "")
proxy.Credentials = new NetworkCredential(tbProxyUsr.Text, tbProxyPwd.Text);
client.Proxy = proxy;
}
Uri uri = new Uri(tbURL.Text);
client.DownloadFile(uri, tblocalFile.Text);
client.Dispose();
HTTP Post Code...
WebClient client = new WebClient();
if (tbpassword.Text != "" && tbUsername.Text != "")
{
NetworkCredential auth = new NetworkCredential(tbUsername.Text, tbpassword.Text);
client.Credentials = auth;
}
if (tbProxyAddress.Text != "" && tbProxyPort.Text != "")
{
WebProxy proxy = new WebProxy(tbProxyAddress.Text, Convert.ToInt32(tbProxyPort.Text));
if (tbProxyUsr.Text != "" && tbProxyPwd.Text != "")
proxy.Credentials = new NetworkCredential(tbProxyUsr.Text, tbProxyPwd.Text);
client.Proxy = proxy;
}
Uri uri = new Uri(tbURL.Text);
System.Collections.Specialized.NameValueCollection collect = new System.Collections.Specialized.NameValueCollection();
collect.Add("input", "Ronak");
collect.Add("submit", "Submit");
byte[] btArray = client.UploadValues(uri, "POST", collect);
//byte[] btArray = client.UploadFile(uri, "POST", tblocalFile.Text);
MessageBox.Show(Encoding.UTF8.GetString(btArray));
client.Dispose();
|
|
|
|
|
Hi all,
I'm working on a project using Visual Studio2005. I have saved an image path to the database. The code is something like this:
-----------------------------------------------
.
.
.
OpenFileDialog openImgFile = new OpenFileDialog();
if (openImgFile.ShowDialog() == DialogResult.OK)
{
imgPath= openImgFile.FileName;
pictureBox1.Image = Image.FromFile(imgPath);
}
cmdStr = "insert into img_tbl(imgID,imgPath)values('01',@path)";
cmd = new SqlCommand(cmdStr, cnn);
SqlParameter path = new SqlParameter("@path", SqlDbType.NVarChar, 225);
path.Value = imgPath;
cmd.Parameters.Add(path);
cmd.ExecuteNonQuery();
.
.
.
What I got from that is an image path storing in the database, something like this:
C:\Documents and Settings\Desktop\foto_311.jpg
But the problem is when I use this path to get an image to display on a form, it dosen't work!
If I change a little like this:
C:\\Documents and Settings\\Desktop\\foto_311.jpg
then it works.
So can anyone tell me how to change it before being saved?
Thankz
|
|
|
|
|
|
The retrieve code not included there
|
|
|
|
|
only two letters away from being an asset
|
|
|
|
|
I have created a addin for outlook 2003 using c# and installing using setup project. How can i prompt user to close outlook if it is open during install/uninstall?
In setup project how can i add this condition?
|
|
|
|
|
You can get all processes by some name:
<br />
Process [] localByName = Process.GetProcessesByName("notepad");<br />
But it is not a strong solution. User can modify name of a file executes an outlook so you didn't get it
|
|
|
|
|
I've noticed a odd problem when using a class that implements IList<T> with a BindingSource. I've managed to reproduce the problem with some simple classes. I have a class called BaseClass and several classes that derive from BaseClass called DerivedClass1, DerivedClass2 and DerivedClass3.
Now I create a class to act as a collection of BaseClass objects called BaseClassCollection. BaseClassCollection implements IList<T> and basically just wraps a List<BaseClass> at this point. At this point everything works fine and I can populate the BaseClassCollection with objects of type DerivedClass1, DerivedClass2 and DerivedClass3 to create a heterogenous collection.
Now the problem comes when I try and use BaseClassCollection as a DataSource for a BindingSource. I create a form with a ListBox control with it's DataSource set to a BindingSource. I then set my BindingSource to bind to an empty BaseClassCollection. Then I add three buttons that will add either a DerivedClass1, DerivedClass2 or a DerivedClass3 object to the collection and refreshes the BindingSource. If I add several objects of the same type then I have no problem, but as soon as I try to add a object of a different class I get an exception:
The value "BindingTest.Derived2" is not of type "BindingTest.Derived1" and cannot be used in this generic collection.
Parameter name: value
It seems that when you set the DataSource of the BindingSource to an IList<T> it looks at the first item in the list (let's say it's a DerivedClass1) and assumes that the list is a DerivedClass1 list and won't let you add anything that isn't a DerivedClass1. What it should do is recognize that it's an IList<baseclass> and assume we have a list of BaseClass and thus allow the addition of any class derived from BaseClass. Oddly enough, if I make my BaseClassCollection inherit from List<BaseClass> instead or implementing IList<BaseClass> then it works as expected, but I lose the ability to control the implemenation of the list.
Does anybody know what is happening here? How do I make the BindingSource realize that it's dealing with a collection of BaseClass?
-- modified at 21:21 Friday 8th June, 2007
Fixed by < and > which completely changed the meaning of the question
|
|
|
|
|