Is it possible to include a conditional expression during List type initialization?

Asked 2 years ago, Updated 2 years ago, 42 views

It is written in C#.NET.
If there is a code like the one below, I would like to use a conditional expression (IF statement) in the middle. Is it possible to write it down?
If possible, how do you write it?

prate List<UserInfo>[ ] usersList=newList<UserInfo>[8];
usersList=newList<UserInfo>{
    new UsersInfo {No=1,FileName="book1.xlsx"sheet=3},
    new UsersInfo {No=2, FileName="book1.xlsx"sheet=3},  
    new UsersInfo {No=3, FileName="book1.xlsx"sheet=4},
    new UsersInfo {No=4, FileName="book1.xlsx"sheet=1}, 
   ★★★ At this time, I would like to change the FileName value of ↑↑↑ by condition★★★
   ↓↓↓ It appears to be written as follows, but in this case, it is not readable when conditions increase.
new UsersInfo {No=4, FileName=(cond==2?"book3.xlsx":"book1.xlsx"), sheet=1)
   ★★★ Is there a way to write in IF?★★★
   ★★★ If I can write, how should I write it?★★★

   :
   :
}

c# .net

2022-09-29 21:48

2 Answers

I can't.

The syntax listed is simply calling the Add method by saying collection initializer, so if you want to include conditions when adding, be honest and call the Add method.


2022-09-29 21:48

Write whatever function you want...
Isn't that what you're looking for?

Func<string>getFileName=()=>
{
    if(cond==2)
    {
        return "book3.xlsx";
    }
    return "book1.xlsx";
};
usersList=newList<UserInfo>{
    newUserInfo() {No=1, FileName="book1.xlsx", sheet=3},
    newUserInfo() {No=1, FileName="book1.xlsx", sheet=3},
    newUserInfo() {No=1, FileName="book1.xlsx", sheet=4},
    newUserInfo() {No=1,FileName=getFileName(),sheet=1}
};


2022-09-29 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.