达到foreach之外的变量

时间:2016-04-15 12:39:12

标签: c# asp.net-mvc linq

我正在使用linq搜索功能。我必须按地点列表搜索(显示来自Tokio,Berlin,New York的学生)。我有一个foreach语句,它将通过所有位置并将它们添加到列表中。我的问题是,除了foreach之外,我不能让他们全部无视。如何在foreach之前声明var newstudents?

贝娄是我的代码

public void search(IEnumerable<string> Location)
{
    foreach (var l in Location)
    {
        var students = from s in db.Students select s;
        students = students.Where(s => s.City.Contains(l));
        var customers = students.ToList();                  
     }
     int custIndex = 1;
     Session["TopEventi"] = customers.ToDictionary(x => custIndex++, x => x);
     ViewBag.TotalNumberCustomers = customers.Count();

4 个答案:

答案 0 :(得分:3)

  

我的问题是我无法在foreach之外显示它们。怎么样   我可以在var newstudents之前声明foreach吗?

为什么你不这样做?您只需要将变量声明为IEnumerable<ClassName>

IEnumerable<Student> customers = null;
foreach (var l in Location)
{
    var students = from s in db.Students
                   where s.City.Contains(l)
                   select s;

    customers = customers.Concat(students);                  
}
customers = customers.ToList()

但是你根本不需要foreach,你可以用一个LINQ查询来完成:

IEnumerable<Student> customers = db.Students
    .Where(s => Location.Any(l => s.City.Contains(l)));

此方法正在Student.City中搜索位置的子字符串。

答案 1 :(得分:2)

彻底摆脱循环。

public void search(IEnumerable<string> Location)
{
       string[] locations = Location.Cast<string>().ToArray();
       var customers = db.Students.Where(s => locations.Contains(s.City)).ToList();

答案 2 :(得分:1)

您可以在foreach之外声明List,并且只执行类似

的操作
yourList.AddRange(students.ToList());

答案 3 :(得分:0)

您可以声明一个字典,用于将您的新学生映射到特定位置,并在循环中为其添加新列表。

你对newstudents这个词的使用有点令人困惑 - 你也不会在这里看到你的代码中的新生只映射他们的位置。无论如何:来自圈外的考生新生:

public void search(IEnumerable<string> Location)
{
    Dictionary<Location, List<Students>> newStudents = new  Dictionary<Location, List<Students>>();
    foreach (var l in Location)
    {
        var students = from s in db.Students select s;
        students = students.Where(s => s.City.Contains(l));
        newStudents[l]= students.ToList();                  
     }
     int custIndex = 1;
    //what is this for?  seeing lastly added 
     Session["TopEventi"] = customers.ToDictionary(x => custIndex++, x => x);
     ViewBag.TotalNumberCustomers = (from  lists in newStudents select  lists.Count).Sum();