简体   繁体   English

根据输入的列表C#动态创建具有属性的对象

[英]Dynamically create object with properties based on inputted List C#

I have a method that takes in two arrays of integers as parameters. 我有一个方法,需要两个整数数组作为参数。 I want to dynamically create objects based on the input. 我想根据输入动态创建对象。 So if user puts in [2,3] and [4,3,2], I want to create 3 new Objects ( Friend2, Friend3 , Friend4). 因此,如果用户输入[2,3]和[4,3,2],我想创建3个新对象(Friend2,Friend3和Friend4)。 I have 2 issues I am stuck with: 我遇到2个问题:

  • Dynamically creating multiple objects with different names based on list items 根据列表项动态创建具有不同名称的多个对象
  • Iterating through two lists and selecting only distinct values of both lists. 遍历两个列表并仅选择两个列表的不同值。

      static int maxTokens( int[] friends_from, int[] friends_to){ **-- Need Code Here to iterate through both arrays and create distinct objects** foreach (var Friend in friends_from and friends_To) { Friend intFriend[i] = new Friend(); } } 

    Is there a way to use Linq to (If not what is the best way to accomplish this?): 有没有办法使用Linq来实现(如果不是,最好的方法是什么?):

  • Save myself from iterating through two lists adding both of them to a third list and selecting distinct 避免自己遍历两个列表,将它们都添加到第三个列表并选择不同的

  • dynamically create object with distinct Name based on listItem 基于listItem动态创建具有唯一名称的对象

You can use union operation to get an array of distinct values like below and then create your object as required 您可以使用联合操作来获取不同值的数组,如下所示,然后根据需要创建对象

 static int maxTokens( int[] friends_from, int[] friends_to)
 {
     var uniqueFriends = friends_from.Union(friends_to).ToArray();

     foreach (var Friend in  uniqueFriends)
     {
        // add your logic for creating instance
     }
  }

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

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