[英]string manipulation to extract substring of particular pattern
我在C#中有以下字符串
Count([AssignedTo]) as [AssignedTo] , Sum([Billing Amount]) as [Billing Amount] , Max([Billing Rate]) as [Billing Rate] , Min([ExecutionDate]) as [ExecutionDate] , Average([HoursSpent]) as [HoursSpent] , [Project], [Sub-Project], [TaskName], [Vendor], [Work Classification], [Work Done], Count([WorkItemType]) as [WorkItemType]
現在我想要通過字符串操作或linq
列出具有聚合函數的所有字段的列表
輸出像
Count([AssignedTo])
Sum([Billing Amount])
Max([Billing Rate])
Min([ExecutionDate])
Average([HoursSpent])
Count([WorkItemType])
也許這對您有用:
var aggr = new []{ "Count", "Sum", "Max", "Min", "Average"};
var allAggregates = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(col => new{ col, token = col.TrimStart().Split().First() })
.Where(x => x.token.Contains('(') && aggr.Any(a => x.token.StartsWith(a, StringComparison.OrdinalIgnoreCase)))
.Select(x => x.token);
我只能獲取功能內部的字段名稱嗎
如果可能,我更喜歡使用字符串方法而不是regex:
var allAggregates = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(col => new { col, token = col.TrimStart().Split().First() })
.Where(x => x.token.Contains('(') && aggr.Any(a => x.token.StartsWith(a, StringComparison.OrdinalIgnoreCase)))
.Select(x => {
string innerPart = x.token.Substring(x.token.IndexOf('(') + 1);
int index = innerPart.IndexOf(')');
if (index >= 0)
innerPart = innerPart.Remove(index);
return innerPart;
});
var aggregates = new []{ "Count", "Sum", "Max", "Min", "Average"};
var output=Regex.Matches(input,@"(\w+)\(.*?\)")
.Cast<Match>()
.Where(x=>aggregates.Any(y=>y==x.Groups[1].Value))
.Select(z=>z.Value);
這是另一種方式:
string[] funcNames = new string[]{"Sum","Average","Count","Max","Min"};
string s = "Your String";
var output = from v in s.Split(',')
where funcNames.Contains(v.Split('(')[0].Trim())
select v.Split(new string[]{" as "},
StringSplitOptions.RemoveEmptyEntries)[0].Trim();
.Split('(')[1].Split(')')[0]; //this line is to get only field names
//Print results
foreach(var str in output) Console.WriteLine(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.