簡體   English   中英

在C#中使用3個數組組織數據

[英]Organizing data with 3 arrays in C#

我正在制作一個自動化數據消息傳遞的程序。

我有一個Excel表,其中包含“名稱”列,“類型列”和“值列”。

看起來像這樣:

Name   Type   Value
Sam    A      32
Ben    B      65
Sam    B      213
max    B      23
max    C      24
max    C      12
Ben    C      45

這些數據不是真實的,但與我正在使用的數據相似。

注意 :某些名稱沒有某些類型。

我已將數據加載到3個數組arrName[]arrType[]arrType[] arrValue[]

我希望使用3D數組arrPro[name, type, value]使數據看起來像這樣。 相同類型的所有值都應屬於同一名稱,並且所有值應加在一起形成一個總值。

將Excel數據直接加載到DataSet是最簡單的方法。

如果您確實想要3D數組,建議將Tuple<string, string, int>作為每一行的數據持有人。

List<Tuple<string, string, int>>將保存您的所有數據。

此結構可能保存您的數據

public class MyTypes
    {
        public string TypeName;
        public List<NamesValues> Names;
    }


    public class NamesValues
    {
        public string Name;
        public List<int> Values;
    }

您應該使用字典。

public Enum EType
{
    A,
    B,
    C
}

public class PatientData
{
    public EType Type { get; set; }
    public int Value {get; set; }
}

public class PatientManager
{
    private readonly Dictionary<String, List<PatientData>> _patients = new Dictionary<String, List<PatientData>>();


    public void AddPatientData(string name, EType type, int value)
    {
            var patientData = new PatientData
                {
                    Type = type,
                    Value = value
                };
            List<PatientData> patientDatas;
            if (!dictionary.TryGetValue(name, out patientDatas))
            {
                patientDatas = new List<PatientData>();
                dictionary.Add(key, patientDatas);
            }
            _patientDatas.Add(patientData);
    }

    public void LoadData(string[] names, EType[] types, int[] values)
    {
        var iMax = Math.Min(names.Length, Math.Min(type.Length, values.Length));
        for (var i = 0; i < iMax; i++)
        {
            AddPatientData(names[i], types[i], values[i]);
        }
    }
}

例如,將數據存儲在某些List<YourObject>並不是更簡單,更干凈的方法

public class YourObject {
    public string Name { get; set; }
    public string Type{ get; set; }
    public int Value { get; set; }
}

然后用linq計算您想要的數量(更少):

List<YourObject> yourObject = "your logic goes here (with whole data)";
List<YourObject> result = from s in yourObject 
    group s by new { s.Name, s. Type) into r
    select new YourObject { Name = r.Name, Type = r.Type, Value = r.Sum(s => s.Value) };

我不確定這正是您要尋找的(分組類型)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM