2016-04-15 43 views
0

我正在使用linq进行搜索功能。我必须通过一系列地点进行搜索(来自Tokio,柏林,纽约的展示学生)。我有一个foreach语句,它通过所有的位置并将它们添加到列表中。我的问题是,我无法对所有这些事情都置之不理。如何在foreach之前声明var newstudents?达到foreach之外的变量

贝娄是我的代码

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(); 
+0

声明'VAR的客户= students.ToList();'前'foreach' –

+0

抱歉,但学生们declaired forecah –

+1

里面然后不!无论如何,所有这些都可以在一行代码中完成。 'var students = db.Students.Where(x => x.City.Any(x => Location.Contains(x));' –

回答

2

摆脱完全循环。

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

OP是使用子字符串搜索,而你正在寻找完整的位置 –

+0

@TimSchmel ter从OP所传递的完整城市名称的问题来看,所以我根据我的回答得出结论。也许这是他们真正想要的? –

+0

不是,OP正在使用's.City.Contains(l)',其中'l'是位置字符串,'Student.City'也​​是'string'。然后它是['String.Contains'](https://msdn.microsoft.com/en-gb/library/dy85x1sa(v = vs.110).aspx)这是一个子字符串搜索,而您的位置.Contains(s .City)'正在使用['List.Contains'](https:// msdn。microsoft.com/en-us/library/bhkz42b3(v=vs.110).aspx),它比较完整的字符串。 –

3

我的问题是,我不能显示他们的foreach所有外。如何 我可以在foreach之前声明var newstudents

为什么你不能这样做?你只需要变量声明为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这是位置的子字符串。

+0

这会覆盖List中的值每个循环或? –

+1

@ConstantinTreiber:true,所以我现在修改了示例以使用'Concat'。但第二种方法似乎好得多。 –

1

你可以申报清单在foreach之外,在侧面你只有这样做

yourList.AddRange(students.ToList()); 
+0

+1为正确答案,但因为它似乎OP没有理解编程这足以解决他的问题,也许你应该扩大你的答案与解释 – Mafii

0

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

此外,您对newstudents这个词的使用有点令人困惑 - 您也无法在此查看代码中的新生只映射其位置。不管怎么说:从外循环considerung新生:

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(); 
+0

如果你想简单地将学生映射到他们来自的城市(这就是你的代码实际做的),最好的答案是@ BarryO'Kane –