AMH
AMH

Reputation: 6451

List of classes question c#

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:

  1. test if all the list items contain the same x
  2. get the list's item that has z = "try"

I need a quick and fast way , instead of iterate though the entire items

Any suggestion please ,

Upvotes: 1

Views: 187

Answers (3)

AndyM
AndyM

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

Jon Skeet
Jon Skeet

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

Vijay Gill
Vijay Gill

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

Related Questions