gpt4 book ai didi

c# - 连接对象数组中的唯一字符串

转载 作者:太空狗 更新时间:2023-10-29 22:12:26 24 4
gpt4 key购买 nike

我有一个包含字符串的对象数组。

var values = new object[5];
values[0] = "PIZZA HUT";
values[1] = "ISLAMABAD";
values[2] = "ISLAMABAD";
values[3] = "PAKISTAN";
values[4] = "PAKISTAN";

我想从数组中获取一串唯一元素,用连接,还需要检查字符串是否为NullOrWhiteSpace;

PIZZA HUT, ISLAMABAD, PAKISTAN. 

目前我正在做以下事情。但是您可以看到它需要在 if 语句中进行大量检查。我想知道是否有使用 LINQ 的更好方法

string featureName = values[0] as string;
string adminboundry4 = values[1] as string;
string adminboundry3 = values[2] as string;
string adminboundry2 = values[3] as string;
string adminboundry1 = values[4] as string;


if (!string.IsNullOrWhiteSpace(adminboundry4)
&& adminboundry4 != adminboundry1
&& adminboundry4 != adminboundry2
&& adminboundry4 != adminboundry3) //want to get rid of these checks
featureName += "," + adminboundry4;

if (!string.IsNullOrWhiteSpace(adminboundry3)) //Not checking for duplicate here just for this question
featureName += "," + adminboundry3;

if (!string.IsNullOrWhiteSpace(adminboundry2)) //Not checking for duplicate here just for this question
featureName += "," + adminboundry2;

if (!string.IsNullOrWhiteSpace(adminboundry1)) //Not checking for duplicate here just for this question
featureName += "," + adminboundry1;

featureName 包含 PIZZA HUT, ISLAMABAD, PAKISTAN, PAKISTAN

最佳答案

您可以使用 string.Join() 方法并从您的对象数组中获取数组不同的字符串元素。

试试这个:

var Result = string.Join(",", values.Cast<string>()
.Where(c => !string.IsNullOrWhiteSpace(c))
.Distinct());

关于c# - 连接对象数组中的唯一字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12214730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com