简体   繁体   English

将数据表与C#列表进行比较

[英]Compare Datatable with C# List

I am working on a MVC project in which i am Stuck with code where i have to compare DataTable value with C# List and Save list value in Sql Database below is my code : 我正在一个MVC项目中,其中我被代码卡住了,我必须将DataTable值与C#列表进行比较,并在下面的Sql数据库中保存列表值是我的代码:

private void AddNumbers(DataTable dTable)
{
    List<NumberRates> aPriceList = new List<NumberRates>();
    NumberRates priceobj = null;

    using (SLDocument sl = new SLDocument(filePath, "Pdf RATES"))
    {
        SLWorksheetStatistics stats = sl.GetWorksheetStatistics();

        for (int row = 11; row <= stats.EndRowIndex; ++row)
        {
            try
            {
                priceobj = new NumberRates();

                priceobj.destination = sl.GetCellValueAsString(row, 1);

                priceobj.a_price = sl.GetCellValueAsDecimal(row, 3);

                aPriceList.Add(priceobj);
            }
        }
    }
}

dTable columns contains name , description And Number dTable列包含名称,描述和编号

Now i want to compare List values with DataTable columns and if list.destination==dTable.description then list.destinatiom = dTble.Number . 现在我想将List值与DataTable列进行比较,如果list.destination == dTable.description然后list.destinatiom = dTble.Number。

Hope I am able to explain my problem . 希望我能解释我的问题。

You just need a loop over the NumberRates list and for each element check if the passed table contains the Destination key. 您只需要在NumberRates列表上循环,并为每个元素检查所传递的表是否包含Destination键。 If you find it then just copy the Number value to the appropriate property of the NumberRates class. 如果找到它,则只需将Number值复制到NumberRates类的适当属性。

foreach(NumberRates element in aPriceList)
{
    DataRow[] match = dTable.Select("Description = '" + element.destination + "'");
    if(match.Length > 0)
        element.Number = match[0].Number;
}

or better, to avoid a second loop just add the above logic to your current code 或更好,为避免第二次循环,只需将上述逻辑添加到当前代码中

for (int row = 11; row <= stats.EndRowIndex; ++row)
{
    try
    {
        priceobj = new NumberRates();

        priceobj.destination = sl.GetCellValueAsString(row, 1);

        priceobj.a_price = sl.GetCellValueAsDecimal(row, 3);

        aPriceList.Add(priceobj);

        DataRow[] match = dTable.Select("Description = '" + priceobj.destination + "'");
        if(match.Length > 0)
           priceobj.Number = match[0].Number;
    }

}

Note, the above code assumes that there is a one-to-one relationship between destination and description. 注意,以上代码假定目标和描述之间存在一对一的关系。 If you have more than one record in your datatable that matches the Description search then you have to specify what you want to do with the values in the other records retrieved by the Select method. 如果您的数据表中有多个记录与“描述”搜索相匹配,那么您必须指定要使用Select方法检索的其他记录中的值要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM