我在下面的c#代码片段中总结了我的问题。我通过review来过滤酒店。我们从用户的逗号分隔值中获取用户评论。目前我循环用户评论并将每个结果合并到单一结果。 现在,我想将循环和linq查询写入单个linq查询。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqST
{
public class Hotel
{
public string Name { get; set; }
public int Review { get; set; }
}
public class DAL
{
public static List<Hotel> Get()
{
return new List<Hotel>()
{
new Hotel{Name="Hotel1",Review=4},
new Hotel{Name="Hotel2",Review=2},
new Hotel{Name="Hotel3",Review=2},
new Hotel{Name="Hotel4",Review=3},
new Hotel{Name="Hotel5",Review=5},
new Hotel{Name="Hotel6",Review=5},
new Hotel{Name="Hotel61",Review=4},
new Hotel{Name="Hotel6",Review=4}
};
}
}
class Program
{
static void Main(string[] args)
{
var filterHotel = "3,4";
var tempList = new List<Hotel>();
foreach (var item in Array.ConvertAll(filterHotel.Split(','), s => int.Parse(s)))
{
var list = DAL.Get().Where(x => x.Review == item);
tempList = tempList.Union(list).ToList();
}
}
}
}
答案 0 :(得分:4)
尝试使用Contains
:
var filteredIds = Array.ConvertAll(filterHotel.Split(','), int.Parse); // or filterHotel.Split(',').Select(int.Parse);
var list = DAL.Get().Where(x => filteredIds.Contains(x.Review));
答案 1 :(得分:3)
听起来你有一个加入,基本上是:
var ratings = filterHotel.Split(',').Select(text => int.Parse(text)).Distinct();
var list = DAL.Get()
.Join(ratings, hotel => hotel.Review, rating => rating,
(hotel, rating) => hotel)
.ToList();
编辑:根据要求,如果单个陈述对您而言比可读性更有价值:
var list = DAL.Get()
.Join(filterHotel.Split(',').Select(text => int.Parse(text)).Distinct(),
hotel => hotel.Review,
rating => rating,
(hotel, rating) => hotel)
.ToList();
或者作为查询表达式:
var list = (from hotel in DAL.Get()
join rating in filterHotel.Split(',')
.Select(text => int.Parse(text))
.Distinct()
on hotel.review equals rating
select hotel).ToList();
答案 2 :(得分:2)
你可以用这个:
tempList = Array.ConvertAll(filterHotel.Split(','), int.Parse)
.Select(item => DAL.Get().Where(x => x.Review == item))
.Aggregate(tempList, (current, list) => current.Union(list).ToList());