c#在List中添加一些值

时间:2014-06-18 06:08:44

标签: c# algorithm linq

我写了一些代码:

List<DataRow> rows=new <DataRow>();
foreach (DataRow dtRow in sqlRows)
{
    foreach (DataRow dtRowId in dttRows1)
    {
        if (Convert.ToInt32(dtRowId[0]) == Convert.ToInt32(dtRow[1]))
            rows.Add(dtParRow);
    }
}

我能写一些更有效的方法吗?可以使用LINQ吗?还是其他一些algorihtm?

P.S。 sqlRows和dttRows1是List。我用表格查询表格:“从表名中选择*”;

3 个答案:

答案 0 :(得分:1)

您可以使用LINQ和连接,这比嵌套方法更有效:

var query = from dtRow in sqlRows
            join dtRowId in dttRows1
              on Convert.ToInt32(dtRow[1]) equals Convert.ToInt32(dtRowId[0])
            select ???; // dtParRow is unknown. Did you mean dtRow?
var list = query.ToList();

请注意,如果这些值已经是int值(因此不需要解析等),那么只需转换:

var query = from dtRow in sqlRows
            join dtRowId in dttRows1
              on (int) dtRow[1] equals (int) dtRowId[0]
            select ???; // dtParRow is unknown. Did you mean dtRow?
var list = query.ToList();

或者使用Field<T> extension method(再次,只有当他们已经int值不需要转换时才会使用

var query = from dtRow in sqlRows
            join dtRowId in dttRows1
              on dtRow.Field<int>(1) equals dtRowId.Field<int>(0)
            select ???; // dtParRow is unknown. Did you mean dtRow?
var list = query.ToList();

答案 1 :(得分:0)

您可以像

那样重写
List<DataRow> rows= (from dtRow in sqlRows 
                     from dtRowId in dttRows1 
                     where Convert.ToInt32(dtRowId[0]) == Convert.ToInt32(dtRow[1])         
                     select dtParRow).ToList();

这并不总是更好的方式。你的代码更加清晰。

答案 2 :(得分:0)

看起来您需要根据条件查找一些项目并将其添加到单独的列表中。

尝试&#34;加入&#34;在LINQ。请看下面的例子。

 public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

 var customerList1 = new List<Customer>(new[]
        {
            new Customer {Id = 1, Name = "AAA"},
            new Customer {Id = 1, Name = "BBB"},
            new Customer {Id = 1, Name = "CCC"}
        });

        var customerList2 = new List<Customer>(new[]
        {
            new Customer {Id = 1, Name = "AAA"},
            new Customer {Id = 1, Name = "BBB"},
            new Customer {Id = 1, Name = "CCC"},
            new Customer {Id = 1, Name = "DDD"}
        });

        var commonCustomers = customerList1.Join(customerList2, x => x.Name, y=>y.Name,(a,b)=>a).ToList();

所以根据你的问题,我认为你应该写的是,(请注意以下代码尚未经过测试)

var rows = sqlRows.Join(dttRows1,x =&gt; Convert.ToInt32(x [0]),y =&gt; Convert.ToInt32(y [0]),(a,b)=&gt; a) .ToList();

谢谢, Cheranga