Skip to main content
 首页 » 编程设计

c#之条件 LINQ 查询获取未分配的变量错误

2024年02月06日12jyk

我从这个问题 (linq with unassigned variable parameters) 中了解到,linq 查询的延迟执行解释了为什么我会收到未分配的变量错误,并且在过去,这段代码作为变通方法运行良好:

    public static void LoadProjects() 
    { 
        CHOCoreDataContext dc = new CHOCoreDataContext(); 
        IEnumerable<ChoCore_Linq_WPF.PROJECT> query1; 
 
        if (((MainWindow)System.Windows.Application.Current.MainWindow).chkShowActive.IsChecked == true) 
        { 
            query1 = 
            from x in dc.PROJECTs 
            orderby x.Experiment_Name 
            where x.Active == "True" //filter for active projects only 
            select x; 
        } 
        else 
        { 
            query1 = 
            from x in dc.PROJECTs 
            orderby x.Experiment_Name 
            select x; 
        } 
 
        List<ProjectID> items = new List<ProjectID>(); 
        foreach (var thing in query1) 
        { 
            items.Add(new ProjectID() { pName = thing.Experiment_Name, pActive = thing.Active, pNotes = thing.Notes }); //creates an "item" with the two properties 
        } 
 
        ((MainWindow)System.Windows.Application.Current.MainWindow).lbxProjects.ItemsSource = items; //bind the listbox to the items list 
    } 

我在 IF 语句之前声明了查询,它工作得很好。但是,在另一种方法中,我尝试使用 SWITCH 语句完成同样的事情:

    public static bool ProjectExists(string myProjectID, modPID _modPID) 
    { 
        CHOCoreDataContext dc = new CHOCoreDataContext(); 
        IEnumerable<ChoCore_Linq_WPF.PROJECT> duplicate; 
 
        switch (_modPID) 
        { 
            case (modPID.addPID): 
                duplicate = 
                   (from x in dc.PROJECTs 
                    where x.Experiment_Name == myProjectID 
                    select x); 
                break; 
            case (modPID.editPID): 
                duplicate = 
                    (from x in dc.PROJECTs 
                     where x.Experiment_Name == myProjectID  
                        && x.PROJECTID_PK != FindProjectKey(myProjectID) 
                     select x); 
                break; 
        } 
 
 
        if (duplicate.Count() == 0) 
        { 
            return false; 
        } 
        else 
        { 
            return true; 
        } 
 
    }   

我在较低的 IF 语句中收到一个错误,变量“duplicate”未分配。我明白这意味着什么,但我不明白为什么它没有被分配。我认为 SWITCH 语句可能会混淆变量的范围,因此尝试使用 IF 语句来构造 linq 查询,但我得到了同样的错误。我是否需要使用 IEnumerable<> 以外的其他方式以不同方式键入查询?或者您能建议我需要做哪些不同的事情吗?

提前致谢!

请您参考如下方法:

你需要一个 default switch case 来为变量赋值,否则它在使用前并没有明确赋值。