Canceling out of a delegate or IComparable

S

superjodash

Hi,

I am sorting a large List<FileInfo> using Sort(new MyComparable()). In
other areas, I'm using an anonymous delegate on a List<>.FindAll(...).

My question is this: How do you cancel out of these scenarios? For
instance, Sort calls the following

public class MyComparable() : IComparer<FileInfo> {
public virtual int Compare(FileInfo x, FileInfo y) {
// i want the cancel here
}
}

The problem is that the Sort method calls this function for each item.
Without throwing an exception, I can't seem to figure out how to stop
the sorting process. Granted, this is probably not a good idea since
it acts directly on the array. However, I still would like to know if
anyone knows how to do it.

Thanks,
John
 
J

Jon Skeet [C# MVP]

I am sorting a large List<FileInfo> using Sort(new MyComparable()). In
other areas, I'm using an anonymous delegate on a List<>.FindAll(...).

My question is this: How do you cancel out of these scenarios? For
instance, Sort calls the following

public class MyComparable() : IComparer<FileInfo> {
public virtual int Compare(FileInfo x, FileInfo y) {
// i want the cancel here
}
}

The problem is that the Sort method calls this function for each item.
Without throwing an exception, I can't seem to figure out how to stop
the sorting process. Granted, this is probably not a good idea since
it acts directly on the array. However, I still would like to know if
anyone knows how to do it.

You can't, basically.

You could write your own CancellableSort routine, which used a
different comparison delegate (or IComparer<T> equivalent) but included
a flag allowing the delegate to cancel - but that's the only option
aside from exceptions.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


Hi,

I am sorting a large List<FileInfo> using Sort(new MyComparable()). In
other areas, I'm using an anonymous delegate on a List<>.FindAll(...).

My question is this: How do you cancel out of these scenarios? For
instance, Sort calls the following

You cannot, basically the List class is doing a loop (for FindAll) in the
collection and ntil it gets to the end it cannot be sure if FindAll will
really find all :)

I'm afraid than an exception is your only alternative, a dirty solution I
might add :(
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top