I have a list of strings:
"55002",
"81512",
"81612",
"84515",
"84615",
"86358",
"86358",
"91128",
"94002"
I want to find in that list items that have the same 2 first characters and the same last characters and then remove from list the one which has lower middle character. In this example the same would be: 81512
and 81612
and I want to remove 81512
, the same would be 84515
and 84615
and I want to remove 84515
etc.
You can try this :
var g = new string[] {"55002", ...};
var t=g.GroupBy(f => f.Substring(0, 2))
.Select(f =>f.OrderByDescending(a =>a ).First());
Result :
55002
91128
81612
84615
86358
94002
update :
I probably missed that groupby should be also mathing the last two charcters .
If that's the case then :
var t=g.GroupBy(f => f.Substring(0, 2)+f.Substring( f.Length-2))
.Select(f =>f.OrderByDescending(a =>a ).First());
For visualization :
Looking at this code :
var g = new string[] {"55002",
"91128",
"81512",
"81712",
"81612",
"84516",
"84216",
"84615",
"86358",
"86358",
"94002"};
var t = g.GroupBy(f => f.Substring(0, 2) + f.Substring(f.Length - 2)).Select(f => new { key = f.Key, group = f.OrderByDescending(a => a)});
Console.Write(t);
We're going to group by the "key" and to take the first top one in each right group :
You can do it like this:
var input = new []{ "1234", "2345" /*...*/};
var res = input.GroupBy(x=> x.Substring(0,2)).Select(x=> x.OrderByDescending(y=>y).ToList()).ToList();
foreach(var l in res)
{
l.RemoveAt(l.Count-1);
}
This will remove last string in literal order, but it will cover your case
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.