Reputation: 79
In my app I have array of objects. Each object contains List
with urls. I want to display Lists
item in that order:
First item from first objects list
First item from second objects list
First item from third objects list
Second item from first objects list
..
etc
Right now I am using foreach
loop:
foreach (Account acc in account)
{
listBox1.Items.Add(acc.ShowData())
}
And public method inside Account
class to get items:
public string ShowData()
{
string singleItem = LinksArray.First();
LinksArray.RemoveAt(0);
return singleItem;
}
It works, but I think there might be more elegant way to do this. Do you have any idea?
Upvotes: 0
Views: 60
Reputation: 2127
A method named ShowData
should never modify the data it is showing. Instead, you might be better served by something like this;
public IEnumerable<String> GetData()
{
return LinksArray;
}
Which you can then use;
foreach(Account acc in accounts)
{
foreach(String data in acc.GetData())
{
// add to listbox items
}
}
This keeps a clear separation between your data and the way it's displayed and read by consumers of the class. It also, optionally, opens you up to using LINQ.
Upvotes: 0
Reputation: 117010
This works for me:
List<Uri>[] arrayOfListsOfUris = ...
IEnumerable<Uri> sorted =
arrayOfListsOfUris
.Select(xs => xs.Select((x, n) => new { x, n }))
.Concat()
.OrderBy(y => y.n)
.Select(y => y.x);
foreach (Uri uri in sorted)
{
//Do something with each Uri
}
Upvotes: 0
Reputation: 78850
Try flattening everything into an set of index/URL pairs, then order by index:
var orderedUrls = objects
.SelectMany(o => o.Urls.Select((url, idx) => new { Index = idx, Url = url }))
.OrderBy(indexedUrl => indexedUrl.Index)
.Select(indexedUrl => indexedUrl.Url)
Upvotes: 2