对象字段包含arrayElements
本文关键字:arrayElements 包含 字段 对象 | 更新日期: 2023-09-27 18:29:55
我有一个数组:
string myArray={"15","56","17-75","78","100-150","130"}
我想通过arrayElements筛选myList。
我想要与以下代码等效的代码,但以编程方式:
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)
首先将字符串转换为更有效的东西来比较:
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];
}
}));
我已经为您准备了一个控制台应用程序。请浏览:
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();
}
}
}