1

我的应用程序中有一个包含 GUID 和 100,000 多条记录表的字符串列表,其中包含一个实体框架模型。

在不存在 GUID 列表的特定数据集中查找所有记录的最有效方法是什么?

以下执行非常缓慢:

var list= new List<string> { "1", "2", "3" };

return (from t1 in db.Items
where (!list.Contains(t1.GUID))
4

2 回答 2

1

当我有很多参数(数百个或更多)查询时,我使用批量插入临时表,然后从主表加入它。

我的代码看起来像这样:

    private static DataTable FillDataTable(IEnumerable<int> keys) {
        var dataTable = new DataTable("Stage");
        dataTable.Locale = CultureInfo.CurrentCulture;
        dataTable.Columns.Add("Key", typeof(int));

        foreach (var key in keys) {
            var row = dataTable.NewRow();
            row[0] = key;
            dataTable.Rows.Add(row);
        }

        return dataTable;
    }

    private static void CreateStageTable(SqlConnection connection, string tableName, DataTable dataTable) {
        var sql = new StringBuilder();
        sql.AppendLine("CREATE TABLE {StageTableName} ( ");
        sql.AppendLine("       Key INT NOT NULL ");
        sql.AppendLine(") ");

        sql.Replace("{StageTableName}", SqlUtilities.QuoteName(tableName));

        using (var command = connection.CreateCommand()) {
            command.CommandText = sql.ToString();
            command.CommandType = CommandType.Text;
            command.ExecuteNonQuery();
        }

        using (var bulkcopy = new SqlBulkCopy(connection)) {
            bulkcopy.DestinationTableName = tableName;
            bulkcopy.WriteToServer(dataTable);
        }
    }


 public void DoQuery(IEnumerable<int> keys) {
      var dataTable = FillDataTable(keys);

       using (var connection = new SqlConnection(_connectionString)) {
            connection.Open();

            CreateStageTable(connection, "#Stage", dataTable);

            string sql =   "SELECT x " +
                           "FROM tbl " +
                           "     LEFT JOIN {StageTableName} AS Stage " +
                           "          ON x.Key = Stage.Key "
                           "WHERE Stage.Key IS NULL";

            ...
        }
 }
于 2013-02-06T12:11:38.467 回答
1

不要使用 a List,使用 a HashSet<string>,这将为您提供O(1)查找而不是O(n)

于 2013-02-06T12:59:49.187 回答