[英]DataCollection or Array of fields from DataCollection or Array of Objects
我有一個實體的數據集合,可以將其轉換為數組,所以我有
DataCollection<Entity> entities;
要么
Entity[] entities;
實體包含幾個字段,例如
string entityName;
int entityNumber;
有沒有辦法創建如下所示的解決方案?
DataCollection<Entity> entities -> DataCollection<int> entityNumbers;
Entity[] entities; -> int[] entityNumbers;
我可以通過foreach做到這一點,例如:
foreach (Entity entity in entities)
{
add entity to new list/collection
}
但是我正在尋找更優雅的解決方案(例如Java中的HashMap)
我認為將我的DataCollection或Array投射到列表中就可以完成工作,因為我們正在尋找一種解決方案:
這個:
List<int> result = list.Select(e => e.i).ToList();
要么:
List<int> result = list.ConvertAll(e => e.i);
從您提到的評論中,您僅在尋找實體編號字段的Sum
。 為此,您可以執行以下操作:
using System.Linq; //at the top of your .cs file
並計算總數。
var total = entities.Sum(x => x.entityNumber);
看看這個:
public class DaCollectionOfInt<T>
{
public int id { get; set; }
}
var result = from m in list select new DaCollectionOfInt<int>() { id = m.id };
要么
var result = list.Select(x=> new DaCollectionOfInt<int>() { id = x.id });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.