user7962273
user7962273

Reputation:

Is there a more efficient way to loop through multiple lists

I have 4 lists of strings - These are all identical in length

var nameList;
var dateList;
var versionList;
var downloadList;

I'm currently looping through each list individually and then adding the contents of each list into a concurrent queue

var concurrentNameQueue= new ConcurrentQueue<string>();
var concurrentDateQueue= new ConcurrentQueue<string>();
var concurrentVersionQueue= new ConcurrentQueue<string>();
var concurrentDownloadQueue= new ConcurrentQueue<string>();

foreach (var name in nameList)
{
    concurrentNameQueue.Enqeue(name);
}

foreach (var date in dateList)
{
    concurrentDateQueue.Enqeue(date);
}

foreach (var version in versionList)
{
    concurrentVersionQueue.Enqeue(version);
}

foreach (var download in downloadList)
{
    concurrentDownloadQueue.Enqeue(download);
}

This process seems awfully repetitive and got me wondering if there is a more efficient way to loop through all these lists

Is there a more efficent way to do this?

Upvotes: 0

Views: 62

Answers (2)

Gilad Green
Gilad Green

Reputation: 37299

  1. You can write an extension method and then call it:

    public static void Enqueue<T>(this ConcurrentQueue<T> queue, IEnumerable<T> items)
    {
        foreach (var item in items)
            queue.Enqueue(item);
    }
    
    concurrentNameQueue.Enqueue(nameList);
    concurrentDateQueue.Enqueue(dateList);
    concurrentVersionQueue.Enqueue(versionList);
    concurrentDownloadQueue.Enqueue(downloadList);
    
  2. Or as you are initializing the list just above then use the second constructor that requires an IEnumerable<T> as input:

    var concurrentNameQueue = new ConcurrentQueue<string>(nameList);
    var concurrentDateQueue = new ConcurrentQueue<string>(dateList);
    var concurrentVersionQueue = new ConcurrentQueue<string>(versionList);
    var concurrentDownloadQueue = new ConcurrentQueue<string>(downloadList);
    

But as I mentioned in my comment it seems like you should create a single class with 4 properties, one for each of name, date, version and download. Then you have one list of that class instead of keeping 4 lists synced.

Upvotes: 2

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

Instead of making multiple list, use data structure that has multiple properties

Thats the advantage of OOP. Create single list of this instead

public class DownloadItem
{
    public string Name { get; set; }
    public string Date { get; set; }
    public string Version { get; set; }
    public string Download { get; set; }
}

Upvotes: 0

Related Questions