从Linq列表中获取对象到新列表

时间:2015-01-29 21:56:04

标签: c# linq list

我正在尝试测试控件中是否存在问题,然后选择要添加到列表中的问题文本。

我列出了20个问题。屏幕上只能看到7个。我想从列表中获取与项目值

对应的对象
  public partial class CustomQuestion
  {

    public string QuestionID { get; set; }
    public string Question { get; set; }
    public string ParentQuestionID { get; set; }
    public int QuestionOrder { get; set; }
    public string ShowOn { get; set; }
    public string Option0 { get; set; }
    public string Option1 { get; set; }
    public string SelectedOption;
  }

 public partial class MultipleChoiceQuestion : UserControl
 {
      public string Answer { get; set; }

      public string Question { get; set; }
 }


 public partial class Form1
 {
    private List<CustomQuestion> MyQuestion = new List<CustomQuestion>();



    private void FindObjects()
    {
   var mylist =  MyQuestion.
      Where(qq => qq.Question == FlowLayouPanel1.Controls.Cast<Control>().
                Where(x => x is MultipleChoiceQuestion).Cast<MultipleChoiceQuestion>().
                    Select(c => c.Question));
    }
 }

我得到的错误是:

      Error 1   Operator '==' cannot be applied to operands of type 'string' and 'System.Collections.Generic.IEnumerable<string>

我希望这足以说明我想要做的事情。如果您有任何问题或要点我可以澄清,请告诉我。

2 个答案:

答案 0 :(得分:4)

您正在尝试将单个问题与一组问题进行比较。你需要做一个交叉点。

为避免重复构建控件中的问题列表20次,请首先使用控件中的问题填充列表:

var controlQuestions = FlowLayouPanel1.Controls
                                      .OfType<MultipleChoiceQuestion>()
                                      .Select(c => c.Question)
                                      .ToList();

然后做交叉点:

var mylist = MyQuestion.Where(q => controlQuestions.Contains(q));

答案 1 :(得分:1)

你需要这样写:

var mylist =  MyQuestion.
  Where(qq => FlowLayouPanel1.Controls.OfType<MultipleChoiceQuestion>().
                Select(c => c.Question).Any(c => qq.Question == c));

然后它将返回MyQuestion

中存在的所有问题
FlowLayouPanel1.Controls
    .OfType<MultipleChoiceQuestion>()
    .Select(c => c.Question)

但这可能取决于你想要达到的目标

原始代码的问题在于您尝试将qq.Question类型的string与右侧表达式返回的List<string>进行比较。但我想你需要检查右表达式是否包含左字符串,所以我的答案是如何制作它的样本