有没有更有效的方法来解决这个问题?
List<String> lstReferences = (from f in
(from section in courseSectionToCreate.SectionsToAdd
select new {
ReferenceNumber = section.Course.CourseNumber.Substring(0, 5) + "." +
section.Course.CourseNumber.Substring(5) + "." +
section.Session + "." +
section.Year + "." +
section.SectionNumber + ";"
})
select f.ReferenceNumber).ToList();
strReferenceNumber = lstReferences.Aggregate((a, b) => a + ", " + b);
答案 0 :(得分:2)
是的,你绝对不想在这里使用Aggregate
。那是O(n^2)
(Schlemiel the Painter's algorithm)。代替:
string referenceNumber = String.Join(", ", lstReferences);
这样做会更好,因为String.Join
会在内部使用StringBuilder
。
答案 1 :(得分:0)
怎么样:
var lstReferences = from section in courseSectionToCreate.SectionsToAdd
let courseNumber = section.Course.CourseNumber
let toJoin = new object[]
{
courseNumber.Substring(0, 5),
courseNumber.Substring(5),
section.Session,
section.Year,
section.SectionNumber
}
select string.Join(".", toJoin) + ";"
var strReferenceNumber = string.Join(", ", lstReferences);
答案 2 :(得分:0)
您可以用以下内容替换所有内容:
var strReferenceNumber =
String.Join(", ",
courseSectionToCreate.SectionsToAdd.Select(s =>
String.Join(".",
s.Course.CourseNumber.Substring(0, 5),
s.Course.CourseNumber.Substring(5),
s.Session,
s.Year,
s.SectionNumber) + ";"
)
);