linq查询中的字符串解析并使用匿名类型
string parsing in linq query and use anonymous type
我有很多这样的对象:
var obj4 = new Data { name = "person", date = DateTime.Now.AddDays(1), data = "pr-214-2-20151224-word2-word3" };
我想编写一个结果如下的 linq 查询:
result=[name=person, date=04/09/2016 12:00:00 AM, data=[2,3]]//2 and 3 are the numbers after word
到目前为止我试过这个:
var listak=new List<Data>{obj,obj2,obj3,obj4};
var u = listak.OrderByDescending(s => s.date).TakeWhile(s => s.date > DateTime.Now).Select(s=>new
{
name=s.name,
date=s.date,
data=s.data.Split(new []{"-"},StringSplitOptions.None).Select(m=>new
{
word = m.Where(c=>m.StartsWith("word")).Select(c=>m.Remove(0,4))//this line is incorrect, i dont know how to correct this part
})
});
但是我得不到我想要的,我该如何实现?
你可以试试这个:
var obj4 = new { name = "person", date = DateTime.Now.AddDays(1), data = "pr-214-2-20151224-word2-word3" };
var listak = new[] { obj4 }.ToList();
var u = listak.OrderByDescending(s => s.date).TakeWhile(s => s.date > DateTime.Now).Select(s => new
{
name = s.name,
date = s.date,
data = s.data.Split(new[] { "-" }, StringSplitOptions.None).Where(c => c.StartsWith("word")).Select(m => m.Remove(0, 4))
});
Console.Write(u);
我有很多这样的对象:
var obj4 = new Data { name = "person", date = DateTime.Now.AddDays(1), data = "pr-214-2-20151224-word2-word3" };
我想编写一个结果如下的 linq 查询:
result=[name=person, date=04/09/2016 12:00:00 AM, data=[2,3]]//2 and 3 are the numbers after word
到目前为止我试过这个:
var listak=new List<Data>{obj,obj2,obj3,obj4};
var u = listak.OrderByDescending(s => s.date).TakeWhile(s => s.date > DateTime.Now).Select(s=>new
{
name=s.name,
date=s.date,
data=s.data.Split(new []{"-"},StringSplitOptions.None).Select(m=>new
{
word = m.Where(c=>m.StartsWith("word")).Select(c=>m.Remove(0,4))//this line is incorrect, i dont know how to correct this part
})
});
但是我得不到我想要的,我该如何实现?
你可以试试这个:
var obj4 = new { name = "person", date = DateTime.Now.AddDays(1), data = "pr-214-2-20151224-word2-word3" };
var listak = new[] { obj4 }.ToList();
var u = listak.OrderByDescending(s => s.date).TakeWhile(s => s.date > DateTime.Now).Select(s => new
{
name = s.name,
date = s.date,
data = s.data.Split(new[] { "-" }, StringSplitOptions.None).Where(c => c.StartsWith("word")).Select(m => m.Remove(0, 4))
});
Console.Write(u);