簡體   English   中英

根據輸入的列表C#動態創建具有屬性的對象

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

我有一個方法,需要兩個整數數組作為參數。 我想根據輸入動態創建對象。 因此,如果用戶輸入[2,3]和[4,3,2],我想創建3個新對象(Friend2,Friend3和Friend4)。 我遇到2個問題:

  • 根據列表項動態創建具有不同名稱的多個對象
  • 遍歷兩個列表並僅選擇兩個列表的不同值。

      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(); } } 

    有沒有辦法使用Linq來實現(如果不是,最好的方法是什么?):

  • 避免自己遍歷兩個列表,將它們都添加到第三個列表並選擇不同的

  • 基於listItem動態創建具有唯一名稱的對象

您可以使用聯合操作來獲取不同值的數組,如下所示,然后根據需要創建對象

 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