在列表中创建重复项 [英] Create duplicate items in a list

查看:87
本文介绍了在列表中创建重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将列表的成员重复X次.

I have the following code to duplicate the members of a list X times.

尽管可以工作,但感觉并不特别干净.

Although it works it doesn't feel particularly clean.

实时代码示例: http://rextester.com/UIVZVX7918

public static List<ServiceEndPoint> GetServiceEndPoints()
{
    const string source = "http://webSiteA.asmx,http://webSiteB.asmx";
    const int instances = 3;

    var splitEndPoints =  source.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                                    .Select((s, i) => new ServiceEndPoint
                                                                {
                                                                    Index = i,
                                                                    Uri = s
                                                                })
                                                                .ToList();

    // Duplicate the contents of splitEndPoints "instances" number of times
    var serviceEndPoints = new List<ServiceEndPoint>();
    foreach (var point in splitEndPoints)
    {
        for (var i = 0; i < instances; i++)
        {
            serviceEndPoints.Add(point);
        }
    }

    return serviceEndPoints;
}

public class ServiceEndPoint
{
    public int Index { get; set; }
    public string Uri { get; set; }
}

有更好的方法吗?

推荐答案

也许与以下内容类似:

var serviceEndPoints = splitEndPoints.SelectMany(t =>
    Enumerable.Repeat(t, instances)).ToList();

这将为您提供"A,A,A,B,B,B,C,C,C".如果要"A,B,C,A,B,C,A,B,C":

That will give you "A,A,A,B,B,B,C,C,C". If you want "A,B,C,A,B,C,A,B,C":

var serviceEndPoints = Enumerable.Repeat(
    splitEndPoints, instances).SelectMany(t => t).ToList();

这篇关于在列表中创建重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆