[英]Get all unique values out of strings
從string
s獲取唯一值時,我遇到了一些問題。
例:
string1 = "4,5"
string2 = "7,9"
string3 = "4,7,6,1"
string4 = "1"
之后,我需要獲取所有唯一值作為int
。 在這種情況下,結果必須為6 。 但是每次字符串的數量都會改變 。
這有可能嗎?
使用Split
和Distinct
var input = "1,3,1,2,3,43,23,54,3,4";
var result input.Split(',')
.Distinct();
Console.WriteLine(string.Join(",",result));
輸出量
1,3,2,43,23,54,4
其他資源
返回一個字符串數組,其中包含此實例中的子字符串,這些子字符串由指定字符串或Unicode字符數組的元素定界。
返回序列中的不同元素。
如果“字符串數可以更改 ”,我們將它們組織成一個集合 :
List<string> strings = new List<string> {
"4,5",
"7,9",
"4,7,6,1",
"1"
};
然后我們可以糾正一個簡單的Linq :
var uniques = strings
.SelectMany(item => item.Split(',')) // split each item and flatten the result
.Select(item => int.Parse(item))
.Distinct()
.ToArray(); // let's have an array of distinct items: {4, 5, 7, 9, 6, 1}
如果要獲取僅顯示一次的項目:
var uniques = strings
.SelectMany(item => item.Split(',')) // split each item and flatten the result
.Select(item => int.Parse(item))
.GroupBy(item => item)
.Where(item => item.Count() == 1)
.Select(group => group.Key)
.ToArray(); // let's have an array of items which appear once: {5, 9, 6}
您可以使用StringBuilder
單個實例來代替使用字符串變量的數量
將所有元素轉換為整數數組。
獲得唯一性/編號,Linq只會出現一次
像這樣:
StringBuilder sb = new StringBuilder();
sb.Append("5,5");
sb.Append(",");
sb.Append("7,9");
sb.Append(",");
sb.Append("4,7,6,1");
sb.Append(",");
sb.Append("1");
string[] arr = sb.ToString().Split(',');
int[] test = Array.ConvertAll(arr, s => int.Parse(s));
var count = test
.GroupBy(e => e)
.Where(e => e.Count() == 1)
.Select(e => e.First()).ToList();
output:
9
4
6
POC: .netFiddler
一行就可以完成工作
string s = "1,3,1,2,3,43,23,54,3,4";
string[] StrArry = s.Split(',');
int[] IntArry = Array.ConvertAll(StrArry, int.Parse).Distinct().ToArray();
輸出
1,3,2,43,23,54,4
他可以試試看嗎
var string1 = "4,5";
var string2 = "7,9";
var string3 = "4,7,6,1";
var string4 = "1";
var allStrings = string1 + ',' + string2 + ',' + string3 + ','+ string4;
var distinctNumbers = new List<string>(allStrings.Split(',').Distinct());
輸出:4 5 7 9 6 1
uniqueNumbers = Count = 6
這是一個比其他更長的時間,但是可能更容易理解它的工作方式。
List<string> str = new List<string> {"1", "3", "1", "2", "3", "43", "23", "54", "3"," "4 };
List<string> foundstr = new List<string> { };
foreach (string check in str)
{
bool found = false;
//going through every single item in the list and checking if it is found in there
for (int i = 0; i < foundstr.Count; i++)
{
//if found then make found(bool) true so we don't put it in the list
if(check == foundstr[i])
{
found = true;
}
}
//checking if the string has been found and if not then add to list
if(found == false)
{
foundstr.Add(check);
}
}
foreach(string strings in foundstr)
{
Console.WriteLine(strings);
}
Console.ReadLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.