开发者

C# foreach question

开发者 https://www.devze.com 2023-02-20 08:35 出处:网络
Does C# has something to offer开发者_StackOverflow中文版 for the following code (in refactoring terms):

Does C# has something to offer开发者_StackOverflow中文版 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);
        }
    }
}


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


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);


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


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);
}


Not efficient:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号