473,785 Members | 2,434 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic List object

We have several generic List objects in our project. Some of them
have about 1000 items in them. Everytime we have to find something,
we have to do a for loop. There is one method which does the
searching, but that method receives the object, and the string to
search in that object and runs the FOR loop to find the answer.

This is taking time because we have to do searching hundres of times.

I want to use Hashtable, but the problem is that I will have to change
158 files. Any suggestion as to what I can do to make my life not so
miserable?

It would be perfect, if I could just make this method faster (for loop
would have to be removed?), or if I could just convert the type from
List to Hashtable in this method and then quickly find it.

Any ideas?

Thanks

Feb 13 '07 #1
7 16669
There is one method which does the
searching, but that method receives the object, and the string to
search in that object and runs the FOR loop to find the answer.

... just convert the type from
List to Hashtable in this method and then quickly find it.
First: for replacing List<T>, you want to use Dictionary<stri ng, T>,
not Hashtable (using string keys as mentioned). With this done, you
would simply have to update this method to use the dictionary methods
(indexer if you strongly believe the item is in the Dictionary;
TryGetValue if you can't be sure).

However! Changing to Dictionary will change a few things; for
instance, it won't be IEnumerable<Tan y more (IIRC it is
IEnumerable<Key ValuePair<TKey, TValue>>, with separate .Keys
and .Values properties). Secondly, the sequence becomes undefined
(Dictionary does not respect insertion order).

Perhaps what you need is something that behaves like a Collection<T>
(since List<Tnot very easy to inherit), but handles an inner
Dictionary? To allow for Add(T), this would mean that the key would
have to be obtainable from the item... hmm...

How about below; is still IEnumerable<T>, etc, but you just need to
update your entities to support the Key, and your search method to use
the indexer (in your case, since no conflict between String and
Int32); if you can't add the Key, then you'd presumably need to change
the Add methods, or use some form of key-provider similar to the hash-
code provider (aka IEqualityCompar er<T>).

Marc

using System;
using System.Collecti ons.ObjectModel ;
using System.Collecti ons.Generic;
static class Program
{
static void Main()
{
IndexedList<str ing, MyDataitems = new IndexedList<str ing,
MyData>();
items.Add(new MyData("Item 1"));
items.Add(new MyData("Item 2"));
items.Add(new MyData("Item 3"));

MyData item = items["Item 2"];
}
}

public class MyData : IKeyed<string>
{
// lazy fields instead of properties...
public MyData(string @ref)
{
Ref = @ref;
}
public readonly string Ref; // key should be immutable for
hashtable
public string Name;
public string AddressLine1;
public int Something;

string IKeyed<string>. Key { get { return Ref; } }
}

public interface IKeyed<T{
T Key {get;}
}
public class IndexedList<TKe y, TValue: Collection<TVal uewhere
TValue : IKeyed<TKey>
{
public TValue this[TKey key] {
get { return _index[key]; }
}
// "get by" for when TKey is int, which causes indexer conflict
public TValue GetByKey(TKey key)
{
return _index[key];
}
public TValue GetByIndex(int index)
{
return base[index];
}
public bool TryGetByKey(TKe y key, out TValue value)
{
return _index.TryGetVa lue(key, out value);
}
public IndexedList(IEq ualityComparer< TKeykeyComparer )
{
_keyComparer = keyComparer ?? EqualityCompare r<TKey>.Default ;
}
public IndexedList() : this(null) { }

private readonly IEqualityCompar er<TKey_keyComp arer;
private readonly Dictionary<TKey , TValue_index = new
Dictionary<TKey , TValue>();
protected override void InsertItem(int index, TValue item)
{
_index.Add(item .Key, item); // checks unique before adding to
either list
base.InsertItem (index, item);
}

protected override void RemoveItem(int index)
{
_index.Remove(t his[index].Key);
base.RemoveItem (index);
}
protected override void ClearItems()
{
_index.Clear();
base.ClearItems ();
}
protected override void SetItem(int index, TValue item)
{
TKey oldKey = this[index].Key, newKey = item.Key;
if (_keyComparer.E quals(oldKey, newKey))
{ // key same; update existing
_index[newKey] = item;
}
else if (_index.Contain sKey(newKey))
{ // key changed but now a duplicate
throw new ArgumentExcepti on("Duplicate key");
}
else
{ // key changed; remove and re-add
_index.Remove(o ldKey);
_index.Add(newK ey, item);
}
base.SetItem(in dex, item);
}
}
Feb 13 '07 #2
IF you want a nice named object, then

public class PersonCollectio n : System.Collecti ons.Generic.Lis t
<Person>

{

}

Below is something cool I found

I found it at:

http://www.google.com/search?hl=en&q...IteratorAction

Matt Berther

using System;

using System.Collecti ons.Generic;

using System.Text;

namespace HowToDoCollecti ons

{

public delegate void IteratorActionD elegate(object sender , Person per);

public class PersonCollectio n : System.Collecti ons.Generic.Lis t <Person>

{

public void Iterate(object sender , IteratorActionD elegate action)

{

foreach (Person p in this)

{

action(sender, p);

}

}

}

}

namespace HowToDoCollecti ons

{

public class Person

{

#region Member Variables

private string _firstName = string.Empty;

private string _lastName = string.Empty;

private string _uid = System.Guid.New Guid().ToString ("N");

#endregion

#region Constructors

public Person()

{

}

public Person(string firstName, string lastName)

{

this.FirstName = firstName;

this.LastName = lastName;

}

#endregion

#region Properties

public string FirstName

{

get { return _firstName; }

set { _firstName = value; }

}

public string LastName

{

get { return _lastName; }

set { _lastName = value; }

}

public string UID

{

get { return _uid; } //ReadOnly

}

#endregion

}

}



class Program

{

private static PersonCollectio n
personCollectio nWithLargerThan MethodScope = new PersonCollectio n();

private static void SayHello(object sender , Person per)

{

Console.WriteLi ne("Hello, {0} {1}", per.FirstName,
per.LastName);

}

private static void TellUserIWasNot Verified(object sender, Person
per)

{

Console.WriteLi ne("NOT VERIFIED : {0} {1}", per.UID,
per.LastName + " " + per.FirstName);

}

private static void VerifyAllPerson s(object sender, Person per)

{

if (per.FirstName. Length <= 0 || per.LastName.Le ngth <= 0)

{

//you need something that lives outside of the method to
track them

personCollectio nWithLargerThan MethodScope.Add (per);

}

}

static void Main(string[] args)

{

try

{

PersonCollectio n p1 = new PersonCollectio n();

p1.Add(new Person("John", "Smith"));

p1.Add(new Person("Cindy", "Brady"));

p1.Add(new Person("", "Madonna")) ;

p1.Add(new Person("Mary", "Jones"));

p1.Add(new Person("Cher", ""));

p1.Iterate(Syst em.Environment. UserName , new
IteratorActionD elegate(SayHell o));

Console.WriteLi ne("\n\r\n\r") ;

p1.Iterate(Syst em.Environment. UserName, new
IteratorActionD elegate(VerifyA llPersons));

personCollectio nWithLargerThan MethodScope.Ite rate(null, new
IteratorActionD elegate(TellUse rIWasNotVerifie d));

}

catch (Exception ex)

{

Console.WriteLi ne(ex.Message);

}

finally

{

Console.WriteLi ne("\n\r\n\rPre ss ENTER to end.");

Console.Read();

}



}

}
Feb 13 '07 #3
Ammendments:

1: remove _keyComparer (not necessary)

2: in the ctor, initialise the Dictionary as follows: _index = new
Dictionary<TKey , TValue>(keyComp arer);

3: replace references to _keyComparer with _index.Comparer

Note that (as per other poster) you can use the Find method on
List<T>, but this still enumerates internally, so O(n); the Dictionary
approach is closer to O(1).

Marc

Feb 13 '07 #4
frick!!! I meant:

_index = new Dictionary<TKey , TValue>(keyComp arer ??
EqualityCompare r<TKey>.Default );

Feb 13 '07 #5
On Feb 13, 4:05 pm, "Sehboo" <MasoodAd...@gm ail.comwrote:
We have several generic List objects in our project. Some of them
have about 1000 items in them. Everytime we have to find something,
we have to do a for loop. There is one method which does the
searching, but that method receives the object, and the string to
search in that object and runs the FOR loop to find the answer.

This is taking time because we have to do searching hundres of times.

I want to use Hashtable, but the problem is that I will have to change
158 files. Any suggestion as to what I can do to make my life not so
miserable?

It would be perfect, if I could just make this method faster (for loop
would have to be removed?), or if I could just convert the type from
List to Hashtable in this method and then quickly find it.

Any ideas?

Thanks
Hi,

Why not use the generic Dictionary collection instead? It use a
hashtable implementation as well.

Do the contents of the List collections change or are they pretty
static? If they are static then you could sort the list once and use
the BinarySearch method.

Also, did you know there was no need to code your own loop for
searching? List already has the Find method.

Brian

Feb 13 '07 #6
if you have 1,000 of anything; put it in a database

C# does not scale well enough to store 1,000 items in memory


On Feb 13, 2:05 pm, "Sehboo" <MasoodAd...@gm ail.comwrote:
We have several generic List objects in our project. Some of them
have about 1000 items in them. Everytime we have to find something,
we have to do a for loop. There is one method which does the
searching, but that method receives the object, and the string to
search in that object and runs the FOR loop to find the answer.

This is taking time because we have to do searching hundres of times.

I want to use Hashtable, but the problem is that I will have to change
158 files. Any suggestion as to what I can do to make my life not so
miserable?

It would be perfect, if I could just make this method faster (for loop
would have to be removed?), or if I could just convert the type from
List to Hashtable in this method and then quickly find it.

Any ideas?

Thanks

Feb 14 '07 #7
Good to see our local troll has a new face

Feb 15 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5444
by: majm | last post by:
I'm trying to implement strongly typed lists in the 2.0 framework. I'm using VS2005 beta 2. So far, System.Collections.Generic.List appears to be the ideal solution. However, the generic.List.IndexOf function doesn't appear to be invoking the contained class' CompareTo method. My understanding is that it should. The contained class (IssStruct) implements the IComparable and IComparable<T> interfaces. However, the List.Sort function...
0
5930
by: crazyone | last post by:
I've got a gaming framework i'm building and i want to save myself the trouble of reading and writting the complete game data to a custom file and load/save it to an XML file but i'm getting problem serializing my stuff to XML when it comes to collections. I'm currently using .net2 with generic lists to prevent users putting all sorts of stuff in the arrays (Although im sure i'll be the only user of the classes but not the game, anyway)....
4
2957
by: rsa_net_newbie | last post by:
Hi there, I have a Managed C++ object (in a DLL) which has a method that is defined like ... Generic::List<String^>^ buildList(String^ inParm) Now, when I compile it, I get "warning C4172: returning address of local variable or temporary". In good old 'C', that would indicate that a 'static' was missing from the declaration of the returned value.
1
1425
by: Deckarep | last post by:
Dear CSharp Group, Both of these techniques work as expected but what is the better way of doing this? Or does it even make a difference? Method 1: public delegate void MyDelegate(string s); //delegate List<MyDelegatelistOfDelegates = new List<MyDelegate>(); //Generic
3
2701
by: Doug | last post by:
I have a generic list object with a property called, "MarkedForDeletion". During the course of my processing, some of the objects in the list will get this property set to true and so at the end I want to loop through my list and remove any object that has this property set to true. Currently I have code like this to accomplish this: List<MyObjectdetails = MyMethodToGetDetails(); MyMethodToMarkDetailsForDeletion();
7
2845
by: =?Utf-8?B?Sm9lbCBNZXJr?= | last post by:
I have created a custom class with both value type members and reference type members. I then have another custom class which inherits from a generic list of my first class. This custom listneeds to support cloning: Public Class RefClass Public tcp As TcpClient Public name As String End Class Public Class RefClassList Inherits List(Of RefClass) Implements ICloneable
4
2299
by: tadmill | last post by:
Hi, Is it possible for a generic list class to use Reflection on the generic type being used to detect a property within that type that refers to the same generic class, only with a different type as the parameter? From various posts and help, this is what I've got so far: public class DataList<T: BindingList<T>
3
9497
by: Taurin | last post by:
I have a method that I would like to be able to pass a generic list (such as List<string>, List<int>, etc). I'm trying to figure out what would be the best type of parameter to use to pass in the list and if there is a way to find out what type of elements it is designed to contain (even if it currently has no elements). How would I go about doing this?
6
3041
by: phancey | last post by:
I want to define a class like this class MyClass { List<TMyList<Twhere T : IMyList {get; set;} } or something like this. I don't want to put <Ton my class definition
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.