示例#1
0
        public List <T> LoadFromCsvFile <T>(string filePath, Encoding code = null, char seperateChar = ',', Dictionary <string, string> mapping = null, Func <string, string> preProcess = null) where T : new()
        {
            if (code == null)
            {
                code = Encoding.UTF8;
            }
            var tl = new List <T>();
            var s  = File.ReadAllText(filePath, code);
            var sl = s.Split('\n');

            if (sl.Length < 2)
            {
                return(tl);
            }
            var pl      = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var priorpl = pl.Where(v => v.GetCustomAttribute(typeof(ColumnMapping)) != null).ToList();
            var head    = sl[0].Trim();
            var bhl     = head.Split(seperateChar);
            var hlist   = new List <string>();

            foreach (var h in bhl)
            {
                hlist.Add(GetPropertyName(h, mapping));
            }

            for (int i = 1; i < sl.Length; i++)
            {
                var t      = new T();
                var record = sl[i].Trim();
                if (!string.IsNullOrEmpty(record))
                {
                    var cl = record.Split(seperateChar);
                    if (cl.Length == hlist.Count)
                    {
                        for (int j = 0; j < hlist.Count; j++)
                        {
                            if (!string.IsNullOrEmpty(hlist[j]))
                            {
                                var cp = priorpl.FirstOrDefault(c => c.Name == hlist[j] || c.GetCustomAttribute <ColumnMapping>().Title == hlist[j]);
                                if (cp == null)
                                {
                                    cp = pl.FirstOrDefault(c => c.Name == hlist[j]);
                                }
                                if (cp != null)
                                {
                                    var value = cl[j];
                                    if (preProcess != null)
                                    {
                                        value = preProcess(cl[j]);
                                    }
                                    CommonProc.SetProperty(t, cp, value);
                                }
                            }
                        }
                        tl.Add(t);
                    }
                }
            }
            return(tl);
        }