【问题标题】:How to assign the same var type variable to different linq to sql result sets?如何将相同的 var 类型变量分配给不同的 linq to sql 结果集?
【发布时间】:2021-11-05 00:01:06
【问题描述】:

我有一个场景:

例如

我有这个

var resultSet;

现在我需要分配给多个 LINQ-SQL 结果,例如

if(somecondition)
{
   resultSet= (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'})
}
if(anotherCondition)
{
   resultSet = (from t2 in table2 where t2.id= 1 select new CustomClass {name='test2'})
}

resultSet= resultSet.OrderByDescending(d => d.Id)
                              .ToArray()

var count= resultSet.Count();

但问题是,如果我在全局范围内使用resultSet,则它不起作用,如果我分配NULL,它将不起作用,因为它不能分配给null,如果我将它分配给var resultSet= new Object(),那么函数 ie .count(), orderby 等将不起作用。

我该怎么办?

我需要对不同的dbcontext 表使用相同的变量,但具有相同的类。

【问题讨论】:

  • var resultSet; 不是有效的 c#。 var 不是类型,它被编译器替换为初始化表达式的类型。变量resultSet 无法更改其类型。
  • 这样的呢? Array 结果集 = null; resultSet= (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'}).ToArray(); resultSet= resultSet.OrderByDescending(d => d.Id) .ToArray();

标签: c# .net entity-framework linq linq-to-sql


【解决方案1】:

您需要将resultSet 定义为IEnumerable<CustomClass>

IEnumerable<CustomClass> resultSet = null;// Must be assigned to something

if(somecondition)
{
   resultSet= (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'})
}
if(anotherCondition)
{
   resultSet = (from t2 in table2 where t2.id= 1 select new CustomClass {name='test2'})
}

resultSet= resultSet.OrderByDescending(d => d.Id)
                              .ToArray()

var count= resultSet.Count();

您也可以选择使用IQueryable&lt;CustomeClass&gt;,但随后您想删除ToArray() 部分。

【讨论】:

    【解决方案2】:

    听起来你想要的是将结果集的范围限定在填充它的代码之外:

    例如,

    public class SomeClass
    {
        public IEnumerable<CustomClass> ResultSet { get; private set; } = new List<CustomClass>();
    
        //Pseudo: values and conditions are just indicative of logic.
        public void SomeMethod(someValue, someOtherValue)
        {
            IQueryable<CustomClass> resultSet = null;
            if(somecondition)
                resultSet = (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'});
           else if(anotherCondition)
                resultSet = (from t2 in table2 where t2.id= 1 select new CustomClass {name='test2'});
           else
               throw new ArgumentException("Invalid combination of conditions.");
             
        ResultSet = resultSet.OrderByDescending(d => d.Id)
            .ToArray();
    
        var count= resultSet.Count;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多