Reputation: 6451
I have a class contain many variables, something like that
class test
{
internal int x , y ;
internal string z;
}
I created a list of this class list<test> c
I want to do the following:
I need a quick and fast way , instead of iterate though the entire items
Any suggestion please ,
Upvotes: 1
Views: 187
Reputation: 3794
You could implement a custom collection class instead of a list, and put the search smarts into this e.g. add a method AllItemsHaveSameX() and a private bool field allItemsHaveSameX expose a dictionary keyed by the search strings with the index of the item that has that value.
When adding/removing items: You would re-evaluate allItemsHaveSameX Add/remove from your private dictionary.
Upvotes: 0
Reputation: 1503479
LINQ to Objects is your friend. For the first:
bool allSameX = list.All(t => t.x == list[0].x);
Test firstTry = list.First(t => t.z == "try");
Test firstTryOrNull = list.FirstOrDefault(t => t.z == "try");
The first one depends on there being at least one value of course. Alternatives might be:
bool allSameX = !list.Select(t => t.x)
.Distinct()
.Skip(1)
.Any();
In other words, once you've gone past the first distinct value of x
, there shouldn't be any more. One nice aspect of this is that as soon as it spots the second distinct value, it will stop looking - as does the first line (the All
version) of course.
LINQ is wonderfully flexible, and well worth looking into closely.
EDIT: If you need to do the latter test ("find an element with a particular value for z") for multiple different values, you might want a dictionary or a lookup, e.g.
// If there are duplicate z values
var lookup = list.ToLookup(t => t.z);
// If z values are distinct
var dictionary = list.ToDictionary(t => t.z);
Without some pre-work, there's no way of performing the queries you want without iterating over at least some of the list.
Upvotes: 15
Reputation: 1518
You can use linq. Here is a link to small examples that will help you a lot for future too http://msdn.microsoft.com/en-us/vcsharp/aa336746
Upvotes: 2