C#使用LINQ

时间:2016-05-03 14:27:49

标签: c# linq csv

我正在使用LINQ读取CSV文件并应用过滤器然后我获取数据但问题是我的计数数据在应用相同过滤器后比较数据时并不总是匹配。我正在使用Excel打开该CSV文件,但我无法确定为什么我的计数和Excel数据不匹配。所以我在这里用CSV文件链接粘贴我的完整代码。如果可能的话,请在下载CSV文件后运行我的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{

    public partial class Form1 : Form
    {
        DataTable oData = null;
        public Form1()
        {
            InitializeComponent();

            oData = new DataTable();
            oData.Columns.Add("Date", typeof(string));
            oData.Columns.Add("Time", typeof(string));
            oData.Columns.Add("Incomming", typeof(string));
            oData.Columns.Add("Outgoing", typeof(string));
            oData.Columns.Add("Miss Call", typeof(string));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TimeSpan StartTime;
            TimeSpan EndTime;
            bool flag=true;
            TimeSpan tsStart = new TimeSpan(09, 00, 00);
            TimeSpan tsEnd = new TimeSpan(17, 30, 0);

            List<PhoneData> oPhoneData = GetPhoneData(@"d:\report.csv");
            bool isFirstTime = false;

            oData.Rows.Clear();
            while (tsStart < tsEnd)
            {
                if (!flag)
                {
                    tsStart = new TimeSpan(tsStart.Hours, tsStart.Minutes, int.Parse("01"));
                }
                flag = false;

                StartTime = tsStart;
                tsStart = tsStart.Add(new TimeSpan(00, 30, 00));
                EndTime = TimeSpan.Parse((tsStart.Hours >= 10 ? tsStart.Hours.ToString() : ("0" + tsStart.Hours.ToString())) 
                    + ":" + (tsStart.Minutes >= 10 ? tsStart.Minutes.ToString() : ("0" + tsStart.Minutes.ToString())) + ":00");


                int incomingCount = (from row in oPhoneData
                                     where row.direction == "I"
                                     && row.Call_Start.TimeOfDay >= StartTime
                                     && row.Call_Start.TimeOfDay <= EndTime
                                     && row.Is_Internal == 0
                                     && row.continuation == 0
                                     && row.call_duration.TotalSeconds > 0
                                     && !row.party1name.Contains("Voice Mail")
                                     && !row.party1name.Contains("VM")
                                     select 1).Count();

                int outgoingCount = (from row in oPhoneData
                                     where row.direction == "O"
                                     && row.Call_Start.TimeOfDay >= StartTime
                                     && row.Call_Start.TimeOfDay <= EndTime
                                     && row.Is_Internal == 0
                                     && row.continuation == 0
                                     && row.party1name != "Voice Mail"
                                     && !row.party1name.StartsWith("VM")
                                     select 1).Count();

                int misscallCount = (from row in oPhoneData
                                     where row.direction == "I"
                                     && row.continuation == 0
                                     && row.Caller.Trim() != string.Empty
                                     && row.Call_Start.TimeOfDay >= StartTime
                                     && row.Call_Start.TimeOfDay <= EndTime
                                     && row.party1name != "Voice Mail"
                                     && !row.party1name.StartsWith("VM")
                                     && !row.party1name.StartsWith("Line")
                                     && row.Park_Time == 0
                                     && row.Called_number == "687220"
                                     select 1).Count();


                DataRow dr = oData.NewRow();
                dr["Date"] = "12-04-2016";
                dr["Time"] = StartTime + "-" + EndTime;
                dr["Incomming"] = incomingCount;
                dr["Outgoing"] = outgoingCount;
                dr["Miss Call"] = misscallCount;
                oData.Rows.Add(dr);
            }
            dgList.DataSource = oData;
            MessageBox.Show("Job Done");
        }

        public List<PhoneData> GetPhoneData(string strFileName)
        {
            return File.ReadLines(strFileName)
                .Skip(1)
                .Where(s => s != "")
                .Select(s => s.Split(new[] { ',' }))
                .Select(a => new PhoneData
                {
                    Call_Start = DateTime.Parse( a[0]),
                    call_duration = TimeSpan.Parse(a[1]),
                    Ring_duration = int.Parse(a[2]),
                    direction = a[4],
                    Is_Internal =Convert.ToInt32( a[8]),
                    continuation = int.Parse( a[10]),
                    party1name = a[13],
                    Caller = a[3],
                    Park_Time = Convert.ToInt32(a[16]),
                    Called_number = a[5]
                })
                .ToList();
        }
    }

    public class PhoneData
    {
        public DateTime Call_Start { get; set; }
        public TimeSpan call_duration { get; set; }
        public Int32 Ring_duration { get; set; }
        public string direction { get; set; }
        public Int32 Is_Internal { get; set; }
        public Int32 continuation { get; set; }
        public string party1name { get; set; }
        public string Caller { get; set; }
        public Int32 Park_Time { get; set; }
        public string Called_number { get; set; }
    }
}

2 个答案:

答案 0 :(得分:3)

为什么不使用CSVhelper将文件解析为列表,然后在列表中执行必要的LINQ?

以下是Documentation来阅读CSV。

答案 1 :(得分:1)

我检查了您的代码,您必须更改列<?php error_reporting(E_ALL); ini_set('display_errors','On'); header('Content-Type: text/plain'); $sToken = @ $_POST['token']; require_once('braintree/lib/Braintree.php'); // modify if going live Braintree_Configuration::environment('sandbox'); // change the next three per your configuration Braintree_Configuration::merchantId('4444hjxm5h27zxdb'); Braintree_Configuration::publicKey('444443c8qcf2wq5p'); Braintree_Configuration::privateKey('4444b76e4bbf8a6f03cb7ace0e812ba'); $result = Braintree_Transaction::sale( [ 'paymentMethodNonce' => $sToken, 'amount' => '100.00', // currency not required because it's determined by the merchant account settings 'customer' => [ 'firstName' => 'John', 'lastName' => 'Doe', 'phone' => '614-111-2222', 'email' => 'example@example.com' ], 'billing' => [ 'firstName' => 'John', 'lastName' => 'Doe', 'streetAddress' => '100 Main Street', 'extendedAddress' => 'Apt A', 'locality' => 'Columbus', 'region' => 'OH', 'postalCode' => '43085', 'countryCodeAlpha2' => 'US' ], 'shipping' => [ 'firstName' => 'John', 'lastName' => 'Doe', 'streetAddress' => '100 Main Street', 'extendedAddress' => 'Apt A', 'locality' => 'Columbus', 'region' => 'OH', 'postalCode' => '43085', 'countryCodeAlpha2' => 'US' ], 'options' => [ 'submitForSettlement' => TRUE ] ] ); print_r($result); 的索引,因为列位置是12而不是13。

所以这一栏的条件是错误的

Party1Name