C# 根据索引从列表中返回一个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9431706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:23:47  来源:igfitidea点击:

C# Return an object from a list based on index

c#list

提问by Gvs

I need to make some changes so that I only retrieve one object at a time from my list instead of the entire list as I do now.

我需要进行一些更改,以便我一次只从列表中检索一个对象,而不是像现在一样检索整个列表。

Right now ive got a private list in class B with a property returning the entire list basically making it public anyway and I want to change this.

现在我在 B 类中得到了一个私有列表,其中一个属性返回整个列表,基本上使它成为公开的,我想改变它。

The way class a looks(the ui class operating with the list) is, I enter some data validate it and send it to class B which in turn packages it into a list of objects based on the input.

类 a 的外观(使用列表操作的 ui 类)的方式是,我输入一些数据对其进行验证并将其发送到类 B,后者又根据输入将其打包成一个对象列表。

Then class A needs to loop this list and add it to a listview for displaying it which looks like this at the moment:

然后类 A 需要循环这个列表并将其添加到一个列表视图中以显示它,目前看起来像这样:

    ListViewItem lvi = new ListViewItem();
        foreach ([Object] o in CLassB.getList())
        {
            lvi = new ListViewItem(o.property0);
            lvi.SubItems.Add(o.property1);
            lvi.SubItems.Add(o.property2);
            lvi.SubItems.Add(o.property3);
        }
    }

Object is my abstract class which controls how the different types of items are added and getList() is my method in class B returning the entire list.

Object 是我的抽象类,它控制如何添加不同类型的项目,getList() 是我在 B 类中返回整个列表的方法。

The thing is these propertys are the common ones all classes share the there are some that arent, like a textbox that you enter specific text about the object and so on which is displayed like this:

问题是这些属性是所有类共享的公共属性,有一些属性没有,例如您输入有关对象的特定文本的文本框等,其显示如下:

    private void lvRegistered_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        if (Listview.SelectedItems.Count > 0)
        {
            foreach ([Object] ob in ClassB.getList())
            {
                if (Listview.SelectedItems[0].SubItems[0].Text == ob.id.ToString())
                {
                    TextBox.Clear();
                    TextBox.Text = ob.property4;
                }
            }
        }
    }

Now this all works great at the moment but now I have a returned list to operate on but I dont want to return the list making it public I want to return one object of the list based on an index number (yes the functionality will be exactly the same, I made a method returning the count of the private list so I can loop over it and return all). This is for practicing OOP for when I dont want to return everything.

现在这一切都很好,但现在我有一个返回的列表进行操作,但我不想返回列表使其公开我想根据索引号返回列表的一个对象(是的,功能将完全相同同样,我创建了一个返回私有列表计数的方法,这样我就可以遍历它并返回全部)。这是为了在我不想返回所有内容时练习 OOP。

How would this be done? All I can think of is making a new list, take an int as input and search my private list and find the index then add that to the other list and return that list, but I dont know if this is good practice or the best way to do it? Well I havent looked into how to "copy" one element over to next list either but might aswell check and see if theres a better way to do things?

这将如何完成?我能想到的就是创建一个新列表,将 int 作为输入并搜索我的私人列表并找到索引,然后将其添加到另一个列表并返回该列表,但我不知道这是好的做法还是最佳方法去做吧?好吧,我还没有研究如何将一个元素“复制”到下一个列表,但不妨检查一下是否有更好的做事方法?

Just get the feeling im "taking the long way around" this way

只是感觉我“走很长的路”这样

采纳答案by ken2k

Not sure to understand, but how about a simple GetByIdmethod?

不确定是否理解,但是一个简单的GetById方法怎么样?

public class Foo
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class Test
{
    private List<Foo> list = new List<Foo>();

    public void Add(Foo foo)
    {
        this.list.Add(foo);
    }

    public Foo GetById(int id)
    {
        return this.list.FirstOrDefault(z => z.Id == id);
    }
}

....

Test test = new Test();
test.Add(new Foo { Id = 1, Name = "1" });
test.Add(new Foo { Id = 2, Name = "2" });
test.Add(new Foo { Id = 3, Name = "3" });

Foo foo2 = test.GetById(2);

回答by Ray

I'm not sure I understand completely, but it sounds like you could resolve this be creating an indexer on class B to return the item you want:

我不确定我是否完全理解,但听起来您可以通过在 B 类上创建索引器来返回您想要的项目来解决这个问题:

public object this[int index] {
  get {
    return list[index];
  }
}

change 'object' to whatever your class type actually is.

将“对象”更改为您的类实际类型。

You can then access the items as if class B was an array:

然后,您可以像 B 类是数组一样访问这些项目:

object item = classB[5];

回答by Makah

1) You can use List.AsReadOnly() Method.

1) 您可以使用 List.AsReadOnly() 方法。

public ReadOnlyCollection<Double> MyList {
        get {
            return myList.AsReadOnly();
        }
}
private List<Double> myList;

2) Use index method in the class.

2)在类中使用索引方法。

public Double this[int index] {
        get {
            return myList[index];
        }
        set {
            myList[index] = value;
        }
 }
private List<Double> myList;

回答by Gvs

Did about the same as suggested by Ken2k but instead I went with this:

与 Ken2k 的建议大致相同,但我选择了这个:

    public [Class] getListItem(int index)
    {
        return myList.ElementAt(id);
    }

which in turn is used in my other class that displays the info like:

反过来,它在我的另一个类中使用,显示如下信息:

    for (int i = 0; i < am.getCount(); i++)
            {
                ListViewItem = new ListViewItem([class reference].getList(i).[property].ToString());
                ListViewItems.SubItems.Add([class reference].getList(i).[property]);
            }

Thanks everyone for all your help on this.

感谢大家在这方面的所有帮助。