简体   繁体   English

c#如何将结构的引用添加到数组或列表?

[英]c# how to add a reference for a struct to an array or list?

New to c# and object oriented I am creating predefined data held in structs (that will not change). c# 和面向对象的新手我正在创建保存在结构中的预定义数据(不会改变)。 and I want to add a reference to those structs in either an array or a list The thought process is to then loop through an array of these structs and if the filter criteria is met, to then add an element of the struct "Displayname" to a listbox Example I am using here is for an array并且我想在数组或列表中添加对这些结构的引用思想过程是然后循环遍历这些结构的数组,如果满足过滤条件,则将结构“Displayname”的元素添加到我在这里使用的列表框示例用于数组

    public struct ListboxData
    {
        public string Category;
        public string Displayname;
        public string ID;
        public List<string> IDTags;
        public string FaultTxt;
        public string Suggestion;
        public string Comments;
        public List<string> MoreQuestions;
    }

    public ListboxData COOLING = new ListboxData
    {
        Category = "CATEGORY",
        Displayname = "COOLING",
        ID = "CAT_COOL",
        IDTags = { ""},
        FaultTxt = "",
        Suggestion = "",
        Comments = "",
        MoreQuestions = { ""}
    };

Having now created multiple instances of the ListboxData structs I then want to add a selection of some of these structs to an array.现在创建了 ListboxData 结构的多个实例,然后我想将其中一些结构的选择添加到数组中。 In this case the Struct reference COOLING在这种情况下,结构参考 COOLING

Example of what I am trying to achieve我正在努力实现的示例

public ListboxData[] ARRAYofCATEGORIES =
{
    COOLING
};

How can I achieve this ?我怎样才能做到这一点?

I re-wrote your example, working.我重写了你的例子,工作。 You can find a live test here您可以在此处找到实时测试

Below is the code.下面是代码。 I used a List() since you mentioned in your question that it was acceptable, and I am more used to it.我使用了 List() ,因为你在你的问题中提到它是可以接受的,我更习惯了。

I don't know what you were doing wrong since you didn't show us a full example.我不知道你做错了什么,因为你没有向我们展示一个完整的例子。 You can read the code bellow, tell me if there is something you don't understand/want and i'll update my answer to fit your needs :-)您可以阅读下面的代码,告诉我是否有您不理解/想要的东西,我会更新我的答案以满足您的需求:-)

Here is the code这是代码

public struct ListboxData { private readonly string _category;公共结构 ListboxData { 私有只读字符串 _category;

    private readonly string _displayname;
    private readonly string _id;
    private readonly List<string> _idTags;
    private readonly string _faultTxt;
    private readonly string _suggestion;
    private readonly string _comments;
    private readonly List<string> _moreQuestions;

    public ListboxData(string category, string displayname, string id, List<string> idTags, string faultTxt, string suggestion, string comments, List<string> moreQuestions)
    {
        _category = category;
        _displayname = displayname;
        _id = id;
        _idTags = idTags;
        _faultTxt = faultTxt;
        _suggestion = suggestion;
        _comments = comments;
        _moreQuestions = moreQuestions;
    }

    public string Category
    {
        get { return _category; }
    }

    public string Displayname
    {
        get { return _displayname; }
    }


    public string Id
    {
        get { return _id; }
    }


    public List<string> IdTags
    {
        get { return _idTags; }
    }


    public string FaultTxt
    {
        get { return _faultTxt; }
    }


    public string Suggestion
    {
        get { return _suggestion; }
    }


    public string Comments
    {
        get { return _comments; }
    }


    public List<string> MoreQuestions
    {
        get { return _moreQuestions; }
    }
}

public class Test
{
    public List<ListboxData> Categories = new List<ListboxData>();
    public CoolingListTest()
    {            
        Categories.Add(new ListboxData(
            category: "CATEGORY",
            displayname: "COOLING",
            id: "CAT_COOL",
            idTags: new List<String> { "" },
            faultTxt: "",
            suggestion: "",
            comments: "",
            moreQuestions: new List<String> { "" }
         ));
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var test = new Test(); 

        Console.WriteLine(test.Categories.First().Displayname);
    }
}

1st rule to go by is that you have to design immutability into struct .要遵循的第一条规则是您必须将不变性设计到struct Especially if the fields are reference types (string, array, user classes).特别是如果字段是引用类型(字符串、数组、用户类)。

I will demonstrate below a simplified example of populating a struct with various values, then creating a collection (array or list) of the struct and then finally slicing one of the values as an array.我将在下面演示一个使用各种值填充结构的简化示例,然后创建该结构的集合(数组或列表),最后将其中一个值切片为数组。

See live code here this code:在此处查看实时代码此代码:

public struct ListboxData
{        
    public ListboxData(
        int id,
        string category,
        string name,
        params string[] tags) : this()
    {
        this.ID = id;
        this.Category = category;
        this.Name = name;
        this.Tags = new List<string>();
        this.Tags.AddRange(tags);
    }      
    public int ID { get; private set; }
    public string Category { get;  private set;}
    public string Name { get;  private set;}
    public List<string> Tags { get;  private set;}

    public string[] ToStringArray() 
    {
        return new[] {
            ID.ToString(),
            Category,
            Name,
            string.Join(";", Tags)
        };
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        //Your code goes here
        Console.WriteLine("Hello, world!");

        var list = new List<ListboxData>();
        list.Add(new ListboxData(1001, "COOLING", "Cooling Intro"));
        list.Add(new ListboxData(1002, "COOLING", "Cooling Adanced"));
        list.Add(new ListboxData(1003, "COOLING", "Cooling Tests"));
        list.Add(new ListboxData(1004, "HEATING", "Heating Intro", "tag1", "tag2"));

        // Get all cooling ID's
        int[] ids = list.Where((item)=> item.Category=="COOLING").Select( (item)=> item.ID).ToArray();
        // { 1001, 1002, 1003 }

        foreach(var item in ids)
        {
            Console.WriteLine(item);
        }

        // Get all items that contain "Intro" in the name
        ListboxData[] intro = list.Where((item)=>item.Name.Contains("Intro")).ToArray();
        // { list[0], list[3] }
        foreach(var item in intro)
        {
            Console.WriteLine(item.Name);
        }
    }
}

Newer versions of have simplifications for the above code.较新版本的对上述代码进行了简化。 You can omit the private set;你可以省略private set; statements in the properties.属性中的语句。

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

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