简体   繁体   English

订单对象清单项目

[英]Order objects List items

In my app I have array of objects. 在我的应用程序中,我有对象数组。 Each object contains List with urls. 每个对象都包含带有URL的List I want to display Lists item in that order: 我想Lists顺序显示Lists项:

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循环:

            foreach (Account acc in account)
            {
                    listBox1.Items.Add(acc.ShowData())
            }

And public method inside Account class to get items: Account类中使用public方法获取项目:

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? 你有什么主意吗?

Try flattening everything into an set of index/URL pairs, then order by index: 尝试将所有内容展平为一组索引/ URL对,然后按索引排序:

var orderedUrls = objects
    .SelectMany(o => o.Urls.Select((url, idx) => new { Index = idx, Url = url }))
    .OrderBy(indexedUrl => indexedUrl.Index)
    .Select(indexedUrl => indexedUrl.Url)

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
}

A method named ShowData should never modify the data it is showing. 名为ShowData的方法永远不要修改其显示的数据。 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. 也可以选择使用LINQ。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM