2012-04-03 97 views
0

我有一个数组:对象字段包含arrayElements

string myArray={"15","56","17-75","78","100-150","130"} 

我要过滤myList中通过arrayElements

我想等同于下面的代码,但编程:

mylist.Where(i=>i.val==15 || i.val==56 || (i.val >= 17 && i.val<75) ||i.val==78 || (i.val >= 100 && i.val<150)|| i.val==130) 

回答

6

首先转换成字符串的东西,是更有效的东西比较:

int[][] spans = 
    myArray.Select(
    s => s.Split('-').Select(v => Int32.Parse(v)).ToArray() 
).ToArray(); 

然后你就可以在比较的品种该列表的值:

list.Where(i => spans.Any(s => { 
    if (s.Length == 1) { 
    return i == s[0]; 
    } else { 
    return i >= s[0] && i <= s[1]; 
    } 
})); 
2

我准备了一个控制台应用程序您。请通过它:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Person 
    { 
     public string Name { get; set; } 
     public int Age { get; set; } 
    } 
class Program 
{ 
    static void Main(string[] args) 
    { 
     IEnumerable<Person> myQuery = null; 
     List<Person> peopleList = new List<Person>(); 

     Person p1 = new Person(); 
     p1.Name = "x"; p1.Age = 15; 
     peopleList.Add(p1); 

     Person p2 = new Person(); 
     p2.Name = "y"; p2.Age = 50; 
     peopleList.Add(p2); 

     string[] myArray = { "15", "56", "17-75", "78", "100-150", "130" }; 
     foreach (string strAge in myArray) 
     { 
      string strLocalAge = strAge; 
      if (!strLocalAge.Contains("-")) 
      { 
       if (myQuery == null) 
       { 
        myQuery = peopleList.Where(p => p.Age == Convert.ToInt32(strLocalAge)); 
       } 
       else 
       { 
        myQuery = myQuery.Union(peopleList.Where(p => p.Age == Convert.ToInt32(strLocalAge))); 
       } 
      } 
      else 
      { 
       string[] agePart = strLocalAge.Split(new char[] { '-' }); 
       if (agePart.Length == 2) 
       { 

        if (myQuery == null) 
        { 
         myQuery = peopleList.Where(p => p.Age >= Convert.ToInt32(agePart[0]) && p.Age <= Convert.ToInt32(agePart[1])); 
        } 
        else 
        { 
         myQuery = myQuery.Union(peopleList.Where(p => p.Age >= Convert.ToInt32(agePart[0]) && p.Age <= Convert.ToInt32(agePart[1]))); 
        } 
       } 
      } 
     } 
     var myresult = myQuery.ToList(); 
     foreach (Person p in myresult) 
     { 
      Console.WriteLine("Name: " + p.Name + " Age: " + p.Age.ToString()); 
     } 

     Console.ReadLine(); 
    } 
} 

}