我有以下字符串:
=+[^=]+=+\n([\w\W]+\n)(?==+[^=]+=+\n)
现在我要创建类似以下的字符串:
"Parent1:Child1"
"Parent1:Child2"
"Parent1:Child3"
"Parent1:Child4"
"Parent2:Child1"
"Parent2:Child2"
"Parent2:Child3"
"Parent2:Child4"
"Parent3:Child1"
"Parent3:Child2"
我尝试了很多方法,但是都无法正常工作。有帮助吗?
答案 0 :(得分:8)
Linq方法
string[] input = { "Parent1:Child1", "Parent1:Child2", "Parent1:Child3", "Parent1:Child4",
"Parent2:Child1", "Parent2:Child2", "Parent2:Child3", "Parent2:Child4",
"Parent3:Child1", "Parent3:Child2"};
Split()
:
的每一项GroupBy()
拆分结果的第一部分(=“ ParentX”):
和Join()
一起赋予代码:
string[] result = input.Select(x => x.Split(':'))
.GroupBy(y => y.First())
.Select(y => y.Key + ":" + string.Join(",",y.Select(z => z.Last())))
.ToArray();
答案 1 :(得分:1)
您可以使用下面的代码来获得以上效果,
offers
在这里,我正在使用ToLookup()将所有匹配的父级作为Key,并将其子级作为值。请阅读有关ToLookup here
的更多信息输出看起来像这样-
mappedBy = "order1"
答案 2 :(得分:0)
您可以用[Fact]
public void RetrievingACustomer_ShouldReturnTheExpectedCustomer()
{
// Arrange
var expectedCustomer = new Customer
{
FirstName = "Silence",
LastName = "Dogood",
Address = new Address
{
AddressLineOne = "The New-England Courant",
AddressLineTwo = "3 Queen Street",
City = "Boston",
State = "MA",
PostalCode = "02114"
}
}.ToExpectedObject();
// Act
var actualCustomer = new CustomerService().GetCustomerByName("Silence", "Dogood");
// Assert
expectedCustomer.ShouldEqual(actualCustomer);
}
分割每个字符串。
使用:
。键将包含父级详细信息,值将包含子级
更易读易懂的东西
Dictionary<string, List<string>>
概念证明:.net Fiddler