2012-04-03 130 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(); 
    } 
} 

}