Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22854

C# foreach question

Does C# has something to offer for the following code (in refactoring terms):

I would like to be able to replace two foreach calls with a single call like for every (x, x) possible pair, can this be done?

foreach (var image1 in sequence.Images)
{
    foreach (var image2 in sequence.Images)
    {
        if (image1 != image2)
        {
            metric.SetImageMetric(new ImagePair(image1, image2), 1.0);
        }
    }
}

Upvotes: 1

Views: 410

Answers (5)

Eric Lippert
Eric Lippert

Reputation: 660513

I'd be inclined to break it up into two phases. First, a query to generate the desired sequence of pairs, and second, a foreach over the sequence:

var pairs = from image1 in sequence.Images
            from image2 in sequence.Images
            where image1 != image2
            select new ImagePair(image1, image2);

foreach(var pair in pairs)
    metric.SetImageMetric(pair, 1.0);

Upvotes: 4

Pete
Pete

Reputation: 11505

Not efficient:

var permutations = sequence.Images.SelectMany (image1 => sequence.Images.Where (image2 => image1 != image2).Select(image2 => new ImagePair (image1, image2)));

Upvotes: 0

Femaref
Femaref

Reputation: 61497

foreach(var pair in sequence.Images
                    .Select(im1 => 
                              sequence.Images.Select(im2 => Tuple.Create(im1, im2))
                    .Where(pair => pair.Item1 != pair.Item2))
{
    metric.SetImageMetric(new ImagePair(pair.Item1, pair.Item2), 1.0);
}

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613562

There's nothing quite as concise as Python's itertools.product(), but you can use Linq, as blogged by Eric Lippert.

Upvotes: 5

Tomas Voracek
Tomas Voracek

Reputation: 5914

There is Zip method http://msdn.microsoft.com/en-us/library/dd267698.aspx

Upvotes: 0

Related Questions