I have this c# code that builds a string of comma seperated matches for a service:
for (m = r.Match(site); m.Success; m = m.NextMatch())
{
found = found + "," + m.Value.Replace(",", "");
}
return found;
Output looks like: aaa,bbb,ccc,aaa,111,111,ccc
Now that code is on .NET 4.0 How can I use C# LINQ to remove duplicates?
Also, Any way to remove duplicates without changing order?
I found this sample code in another post, but not sure exactly how to apply it:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
Thanks.
string[] s = found.Split(',').Distinct().ToArray()
Rewrite the code that builds the result to output it directly.
ie. rewrite this:
for (m = r.Match(site); m.Success; m = m.NextMatch())
{
found = found + "," + m.Value.Replace(",", "");
}
return found;
To this:
return (from Match m in r.Matches(site)
select m.Value.Replace(",", "")).Distinct().ToArray();
This will return an array. If you still want it back as a string:
return string.Join(", ", (from Match m in r.Matches(site)
select m.Value.Replace(",", "")).Distinct().ToArray());
You may or may not be able to remove the last .ToArray() from the last code there depending on the .NET runtime version. .NET 4.0 string.Join(...) can take an IEnumerable<string>, whereas previous versions requires an array.
This will return a string of comma seperated values without duplicates:
var result = string.Join(",",
r.Matches(site)
.Cast<Match>()
.Select(m => m.Value.Replace(",", string.Empty))
.Distinct()
);
this could be one possible solution:
var data = new List<string>();
for (m = r.Match(site); m.Success; m = m.NextMatch())
data.Add(m.Value.Replace(",", ""));
return String.Join(",", data.Distinct().ToArray());
You can achieve this in a single LINQ query
string strSentence = "aaa,bbb,ccc,aaa,111,111,ccc";
List<string> results = (from w in strSentence.Split(',') select w).Distinct().ToList();
Related
From a given list of strings I need to use LINQ to generate a new sequence of strings, where each string consists of the first and last characters of the corresponding string in the original list.
Example:
stringList: new[] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" },
expected: new[] { "ee", "fg", "jw" });
list2 = stringList.Select(e => {e = "" + e[0] + e[e.Length - 1]; return e; }).ToList();
This is what I've tried, it works, but I need to use LINQ to solve the problem and I'm not sure how to adapt my solution.
just for the sake of completeness here is a version using Zip
var stringList = new string [] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" };
var result = stringList.Zip(stringList, (first, last) => $"{first.First()}{last.Last()}");
As mentioned in the comment that Select is already part of LINQ, you can use this code.var output = arr.Select(x => new string(new char[] { x.First(), x.Last() })).ToList();
Here you go:
var newList = stringList.Select(e => $"{e[0]}{e[e.Length - 1]}").ToList();
Approach with LINQ and String.Remove():
string[] input = new[] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" };
string[] result = input.Select(x => x.Remove(1, x.Length - 2)).ToArray();
I'm attempting to remove white space from a post code field in a database so that when I compare it to the users input I'm comparing both strings with no spaces in the post code at all so it shouldn't matter how the post code is entered.
This is my LINQ query with the replace function that doesn't appear to be working:
List<SchoolReferanceDTO> res = db.SchoolReferences.Where(x => x.SchoolReferencePostcode.Replace(" ", "").Contains(Postcode)).Select(x => new SchoolReferanceDTO()
{
SchoolReferenceSchoolId = x.SchoolReferenceSchoolId,
SchoolReferenceEstablishmentName = x.SchoolReferenceEstablishmentName,
SchoolReferenceStreet = x.SchoolReferenceStreet,
SchoolReferenceLocality = x.SchoolReferenceLocality,
SchoolReferenceAddress3 = x.SchoolReferenceAddress3,
SchoolReferenceTown = x.SchoolReferenceTown,
SchoolReferenceCounty = x.SchoolReferenceCounty,
SchoolReferencePostcode = x.SchoolReferencePostcode,
SchoolReferenceEmail = x.SchoolReferenceEmail
}).ToList();
And the string I'm comparing it to:
postcode = postcode.Replace(" ", string.Empty);
One approach is to drop Replace, and use LIKE instead. Since postal codes are generally short, you could transform the target code ST14BJ to %S%T%1%4%B%J% (demo), and use LIKE operator:
var postPattern = Regex.Replace(postcode, "(?<=.|^)(?=.|$)", "%");
List<SchoolReferanceDTO> res = db.SchoolReferences
.Where(x => SqlFunctions.PatIndex(postPattern, x.SchoolReferencePostcode) >= 0)
.Select(...);
I have an array of words
string[] words = { "believe", "relief", "receipt", "field" };
How to find out the words with the substring "ei" using linq
IEnumerable<string> iswordlist = from word in words where words.All(a => a.Contains("ei"))
select word;
foreach (var i in iswordlist)
{
txtlinq.Text = txtlinq.Text + i.ToString();
}
I tried the above but got no result. Can anyone help me on this?
Try like this
var newWord = words.Where(o => o.Contains("ei"));
I'm not very good with free form, but with dot syntax this will work:
var ieWords = words.Where(a => a.Contains("ei"));
Your current code won't even compile because you are using Enumarbale.All method which returns either true or false (when given condition matches) and not an IEnumerable on which you can query. You simple need a Where clause.
Try this:-
var result = words.Where(x => x.Contains("ei"));
Or if you prefer query syntax:-
IEnumerable<string> result = from word in words
where word.Contains("ei")
select word;
Working Fiddle.
My values come from ComboBox:
2|722|742|762|77
I delete unnecessary characters as follows:
foreach (var item in checkListBox)
{
string[] list = item.Split(
new string[] { "2|" },
StringSplitOptions.RemoveEmptyEntries);
}
My list values result:
"72"
"74"
"76"
"77"
My question is:
how can I get all of the above values in 1 row (next to each other) separated by comma like this:
72,74,76,77
?
It sounds like you just want string.Join:
string commaSeparated = string.Join(",", list);
(Note that this is not part of LINQ - it's not the same kind of "join" as for joining multiple sequences. It's joining several strings together with a separator.)
While you can do this in a single statement as per the currently accepted answer, I'd personally consider leaving your existing statement and having this as a separate step. It makes the code easier to both read and debug.
String.Join(",",list);
Though: a) This is not Linq. b) As is mentioned in another answer here - It would be simpler in this case to use Replace.
Using Linq:
list.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(',');
How about
var result = string.Join(",", item.Split(new string[] { "2|" }, StringSplitOptions.RemoveEmptyEntries));
Just use Replace directly:
string input = "2|722|742|762|77";
var result = input.Replace("2|",",").Trim(',');
As noted in the other answers, string.Join is what should be used here. If you'd however insist on LINQ:
var result = list
.Skip(1)
.Aggregate(
list.FirstOrDefault() ?? string.Empty,
(total, current) => total + "," + current);
Given a list of strings like this
"Val.1.ValueA"
"Val.1.ValueB"
"Val.1.ValueC"
"Val.2.ValueA"
"Val.2.ValueB"
"Val.2.ValueC"
"Val.3.ValueA"
"Val.3.ValueB"
"Val.3.ValueC"
How can I write a linq groupby statement to group by the first part of the string including the number? In other words, in the above case I want a list of 3 groups Val.1, Val.2, Val.3
Use String.Split() to define your group key:
var groups = myList.GroupBy(x => { var parts = x.Split('.');
return parts[0] + parts[1]; });
This would work regardless of the length of both parts of the key (before and after the dot).
Edit in response to comment:
It sounds like you want to group by a number within the string, but you do not know in advance which part constitutes the number. In this case this should work:
var groups = myList.GroupBy(x =>
{
var parts = x.Split('.'));
int num = 0;
return parts[0] + parts.Where(p => p.All(char.IsDigit)
.First( p => int.TryParse(p, out num));
}
);
Without more information about the formatting, the simplest is:
var groups = list.GroupBy(s => s.Substring(0, 5));
If these are in fact not fixed length:
var groups = list.GroupBy(s => {
var fields = s.Split('.');
return String.Format("{0}.{1}", fields[0], fields[1]);
});