I've got a console app which updates a column in the database called InstagramId based off user input. I want to be able to query the database and if there's a instagramId which is null, to update it with the correct instagramID based off their instagramUsername.
I wasn't sure on the approach if I should create a fake table based off all the null instagramIds and then use those to update my column or if theres another cleaner approach. This console app is only a one time use so just a quick fix up.
class Program
{
static async Task Main(string[] args)
{
// receive a profile name
var tasks = new List<Task<InstagramUser>>();
foreach (var arg in args)
{
if (string.IsNullOrEmpty(arg)) continue;
var profileName = arg;
var url = $"https://instagram.com/{profileName}";
tasks.Add(ScrapeInstagram(url));
}
try
{
var instagramUsers = await Task.WhenAll<InstagramUser>(tasks);
foreach (var iu in instagramUsers)
{
iu.Display();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static async Task<InstagramUser> ScrapeInstagram(string url)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
// create html document
var htmlBody = await response.Content.ReadAsStringAsync();
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(htmlBody);
// select script tags
var scripts = htmlDocument.DocumentNode.SelectNodes("/html/body/script");
// preprocess result
var uselessString = "window._sharedData = ";
var scriptInnerText = scripts[0].InnerText
.Substring(uselessString.Length)
.Replace(";", "");
// serialize objects and fetch the user data
dynamic jsonStuff = JObject.Parse(scriptInnerText);
dynamic userProfile = jsonStuff["entry_data"]["ProfilePage"][0]["graphql"]["user"];
//Update database query
string connectionString = #"Server=mockup-dev-db";
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("Update ApplicationUser Set InstagramId = '" + userProfile.id + "'" + "where Instagram = '" + userProfile.username + "'", con);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
// create an InstagramUser
var instagramUser = new InstagramUser
{
FullName = userProfile.full_name,
FollowerCount = userProfile.edge_followed_by.count,
FollowingCount = userProfile.edge_follow.count,
Id = userProfile.id,
url = url
};
return instagramUser;
}
else
{
throw new Exception($"Something wrong happened {response.StatusCode} - {response.ReasonPhrase} - {response.RequestMessage}");
}
}
}
}
}
It seems like there are two problems here
Retrieving a list of username from the DB which have null instagram IDs
For each of these, downloading and populating the instagram ID
It looks like you've already solved 1, so let's look at number 2:
This data can be fetched using an SQL query:
SELECT Instagram FROM ApplicationUser WHERE InstagramId IS NULL
In C# this could look like:
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT Instagram FROM ApplicationUser WHERE InstagramId IS NULL", con);
cmd.Connection.Open();
var instagramUsernames = new List<string>();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
instagramUsernames.Add(reader.GetString(0));
}
}
Now you have all the usernames in the instagramUsernames list and can execute your existing code (with minor modifications) in a foreach loop.
Instead of looping through the args you'd now loop through the list of instagramUsernames (so the above code would come at the start of the Main method):
foreach (var arg in args)
Would become foreach (var arg in instagramUsernames)
Related
I'm trying to populate list from mysql with the below code. My model looks like this https://pastebin.com/iQEVV42C
My goal is to populate the lists then take the sub lists and put them into the root (tickets) how can I do this?
public static async Task<IEnumerable<Models.Zelkon.Tickets.Root>> Tickets(int ticketId = 0, int clientId = 0)
{
DataSet ds = new DataSet();
List<Models.Zelkon.Tickets.Root> tickets = new List<Models.Zelkon.Tickets.Root>();
List<Models.Zelkon.Tickets.Incidents> ticketIncidents = new List<Models.Zelkon.Tickets.Incidents>();
List<Models.Zelkon.Tickets.Files> ticketFiles = new List<Models.Zelkon.Tickets.Files>();
List<Models.Zelkon.Tickets.Comments> ticketComments = new List<Models.Zelkon.Tickets.Comments>();
using (MySqlConnection con = new MySqlConnection(Variables.conString))
{
await con.OpenAsync();
string query = "SELECT * FROM tickets;" +
"SELECT * FROM ticket_incidents;" +
"SELECT * FROM ticket_files;" +
"SELECT * FROM ticket_comments;";
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
{
// tickets
while (await reader.ReadAsync())
{
tickets.Add(new Models.Zelkon.Tickets.Root()
{
header_text = reader.GetString("name"),
description = reader.GetString("description"),
status = reader.GetString("status"),
source = reader.GetString("source"),
owner = reader.GetString("owner"),
temp = reader.GetString("temp"),
priority = reader.GetString("priority"),
category = reader.GetString("category"),
creation_team = reader.GetString("creation_team"),
last_updated = reader.GetDateTime("last_updated"),
creation_date = reader.GetDateTime("creation_date"),
client_id = reader.GetInt32("client_id"),
ticket_id = reader.GetInt32("ticket_id"),
unique_id = reader.GetInt32("unique_id")
});
}
await reader.NextResultAsync();
// ticket_incidents
while (await reader.ReadAsync())
{
ticketIncidents.Add(new Models.Zelkon.Tickets.Incidents()
{
header_text = reader.GetString("header_text"),
description = reader.GetString("description"),
type = reader.GetString("type"),
creation_team = reader.GetString("creation_team"),
created_by = reader.GetString("created_by"),
notify_team = reader.GetInt32("notify_team"),
notification_seen = reader.GetInt32("notification_seen"),
is_pinned = reader.GetInt32("is_pinned"),
creation_date = reader.GetDateTime("creation_date"),
incident_id = reader.GetInt32("incident_id"),
ticket_id = reader.GetInt32("ticket_id"),
unique_id = reader.GetInt32("unique_id")
});
}
await reader.NextResultAsync();
// ticket_files
while (await reader.ReadAsync())
{
// Not filled yet
}
await reader.NextResultAsync();
// ticket_comments
while (await reader.ReadAsync())
{
// Not filled yet
}
await reader.NextResultAsync();
}
}
}
System.Diagnostics.Debug.WriteLine(tickets.First().owner);
return tickets;
}
My issue is how I can fill the sub classes (ticket_incidents, ticket_files, ticket_comments) and then put it into the root class?
Firstly, you might save a lot of time by using an ORM to query your database; it will turn a set of related tables into an object graph.
Secondly, if you're going to avoid a full ORM and read the data directly via ADO.NET, I would recommend Dapper, which will remove a lot of boilerplate code.
Here's how the main body of your method would look with Dapper:
string query = "SELECT * FROM tickets;" +
"SELECT * FROM ticket_incidents;" +
"SELECT * FROM ticket_files;" +
"SELECT * FROM ticket_comments;";
using var gridReader = await con.QueryMultipleAsync(query);
// NOTE: Assumes database columns are named exactly the same as the object properties
var tickets = (await gridReader.ReadAsync<Models.Zelkon.Tickets.Root>()).ToList();
var ticketIncidents = (await gridReader.ReadAsync<Models.Zelkon.Tickets.Incidents>()).ToList();
var ticketFiles = (await gridReader.ReadAsync<Models.Zelkon.Tickets.Files>()).ToList();
var ticketComments = (await gridReader.ReadAsync<Models.Zelkon.Tickets.Comments>()).ToList();
Thirdly, if you're using async with MySQL, uninstall Oracle's MySQL Connector/NET (i.e., MySql.Data) and use MySqlConnector instead. It's a longstanding bug in Connector/NET that async operations actually operate completely synchronously.
Finally, to link your objects together, iterate over each collection and attach the object to the right Root object. One way to do this would be to put your Root objects in a Dictionary keyed on their ID:
var ticketsById = tickets.ToDictionary(x => x.ticket_id, x => x);
foreach (var incident in ticketIncidents)
ticketsById[incident.ticket_id].incidents.Add(incident);
foreach (var file in ticketFiles)
ticketsById[file.ticket_id].files.Add(file);
foreach (var comment in ticketComments)
ticketsById[comment.ticket_id].comments.Add(comment);
This assumes that the Root object has an incidents property (files, comments) that's initialized to an empty List<Incidents> (List<Files>, List<Comments>). You will need to write that code if it doesn't exist.
Again, any decent ORM (Entity Framework, NHibernate, etc.) will provide all of this code for you "out of the box", so you wouldn't even have to write this method at all.
I am new to React and new to Web API. I am uploading data in a tabulator in react front end from the value that I am passing through the web API. I am passing value through the getReports function like this:
[HttpPost]
[Route("GetReports")]
public IHttpActionResult GetReports(string jwt, List<object> data)
{
if (!Common.VerificationToken.VerifyJWToken(jwt))
{
return null;
}
var to = data[0];
var from = data[1];
DateTime toDate = Convert.ToDateTime(to);
DateTime fromDate = Convert.ToDateTime(from);
var ReportData = db.T_CQL_COIL_DESC.Where(t => t.CCD_CREATED_ON >= toDate &&
t.CCD_CREATED_ON <= fromDate).ToList();
ReportsDTO dto = new ReportsDTO();
List<ReportsDTO> ReportDTO = new List<ReportsDTO>();
try
{
foreach (var report in ReportData)
{
List<vehicledetail> vehicle = new List<vehicledetail>();
var imgurl = "https://firebasestorage.googleapis.com/v0/b/tsl-coil-qlty-
monitoring-dev.appspot.com/";
dto = new ReportsDTO();
dto.Type = report.CCD_OP_TYPE;
dto.ID = report.CCD_COIL_ID;
vehicle = GetVehicleID(dto.ID);
vehicledetail vehicledetails = vehicle[0];
dto.vehicleno = vehicledetails.vehicleno.ToString();
dto.wagonno = vehicledetails.wagonno.ToString();
dto.Active = report.CCD_ACTIVE;
dto.ImgURL = report.CCD_IMAGE_URL != null ? imgurl + report.CCD_IMAGE_URL : "NA";
dto.Desc = report.CCD_VIEW_DESC != null ? report.CCD_VIEW_DESC : "NA";
ReportDTO.Add(dto);
}
return Ok(ReportDTO);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
}
The data in vehicledetail in vehicledetail vehicledetails = vehicle[0]; is getting populated from this function:
public List<vehicledetail> GetVehicleID(string coilID)
{
List<vehicledetail> vehicle = new List<vehicledetail>();
vehicledetail vehicledetails = new vehicledetail();
string oradb = Utilities.STAR_DB;
OracleConnection conn = new OracleConnection(oradb);
string query = "SELECT a.Vbeln, b.WAGON_NO FROM sapr3.lips a, sapr3.ZVTRRDA b WHERE
a.MANDT='600' AND a.CHARG='" + coilID + "' AND a.LFIMG > 0 AND a.MANDT = b.MANDT AND
a.VBELN = b.VBELN";
OracleDataAdapter da = new OracleDataAdapter(query, conn);
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
vehicledetails.vehicleno = row["VBELN"].ToString();
vehicledetails.wagonno = row["WAGON_NO"].ToString();
}
conn.Close();
vehicle.Add(vehicledetails);
return (vehicle);
}
It is working fine but it is taking 30 seconds to load the below data:
How do I optimize this . Please help. Note: that it is taking 30 seconds to upload this data
Few other things aside, the major problem seems to be that you are querying database for each vehicle.
In this particular scenario it might very well be better to select all vehicle ids and query them all.
var vehicleIds = reportData.SelectMany(t => t.ID);
You can then form a query that will get all vehicle details together. This will reduce the number of database calls and it can have massive impact on time.
Another thing to check is if there's any index created on the vehicle id column in database as that may also help speed things up.
I am using MySQLClient with a local database. I wrote a method which returns a list of data about the user, where I specify the columns I want the data from and it generates the query dynamically.
However, the reader is only returning the column names rather than the actual data and I don't know why, since the same method works previously in the program when the user is logging in.
I am using parameterised queries to protect from SQL injection.
Here is my code. I have removed parts which are unrelated to the problem, but i can give full code if needed.
namespace Library_application
{
class MainProgram
{
public static Int32 user_id;
static void Main()
{
MySqlConnection conn = LoginProgram.Start();
//this is the login process and works perfectly fine so i won't show its code
if (conn != null)
{
//this is where things start to break
NewUser(conn);
}
Console.ReadLine();
}
static void NewUser(MySqlConnection conn)
{
//three types of users, currently only using student
string query = "SELECT user_role FROM Users WHERE user_id=#user_id";
Dictionary<string, string> vars = new Dictionary<string, string>
{
["#user_id"] = user_id.ToString()
};
MySqlDataReader reader = SQLControler.SqlQuery(conn, query, vars, 0);
if (reader.Read())
{
string user_role = reader["user_role"].ToString();
reader.Close();
//this works fine and it correctly identifies the role and creates a student
Student user = new Student(conn, user_id);
//later i will add the logic to detect and create the other users but i just need this to work first
}
else
{
throw new Exception($"no user_role for user_id - {user_id}");
}
}
}
class SQLControler
{
public static MySqlDataReader SqlQuery(MySqlConnection conn, string query, Dictionary<string, string> vars, int type)
{
MySqlCommand cmd = new MySqlCommand(query, conn);
int count = vars.Count();
MySqlParameter[] param = new MySqlParameter[count];
//adds the parameters to the command
for (int i = 0; i < count; i++)
{
string key = vars.ElementAt(i).Key;
param[i] = new MySqlParameter(key, vars[key]);
cmd.Parameters.Add(param[i]);
}
//runs this one
if (type == 0)
{
Console.WriteLine("------------------------------------");
return cmd.ExecuteReader();
//returns the reader so i can get the data later and keep this reusable
}
else if (type == 1)
{
cmd.ExecuteNonQuery();
return null;
}
else
{
throw new Exception("incorrect type value");
}
}
}
class User
{
public List<string> GetValues(MySqlConnection conn, List<string> vals, int user_id)
{
Dictionary<string, string> vars = new Dictionary<string, string> { };
//------------------------------------------------------------------------------------
//this section is generating the query and parameters
//using parameters to protect against sql injection, i know that it ins't essential in this scenario
//but it will be later, so if i fix it by simply removing the parameterisation then im just kicking the problem down the road
string args = "";
for (int i = 0; i < vals.Count(); i++)
{
args = args + "#" + vals[i];
vars.Add("#" + vals[i], vals[i]);
if ((i + 1) != vals.Count())
{
args = args + ", ";
}
}
string query = "SELECT " + args + " FROM Users WHERE user_id = #user_id";
Console.WriteLine(query);
vars.Add("#user_id", user_id.ToString());
//-------------------------------------------------------------------------------------
//sends the connection, query, parameters, and query type (0 means i use a reader (select), 1 means i use non query (delete etc..))
MySqlDataReader reader = SQLControler.SqlQuery(conn, query, vars, 0);
List<string> return_vals = new List<string>();
if (reader.Read())
{
//loops through the reader and adds the value to list
for (int i = 0; i < vals.Count(); i++)
{
//vals is a list of column names in the ame order they will be returned
//i think this is where it's breaking but im not certain
return_vals.Add(reader[vals[i]].ToString());
}
reader.Close();
return return_vals;
}
else
{
throw new Exception("no data");
}
}
}
class Student : User
{
public Student(MySqlConnection conn, int user_id)
{
Console.WriteLine("student created");
//list of the data i want to retrieve from the db
//must be the column names
List<string> vals = new List<string> { "user_forename", "user_surname", "user_role", "user_status"};
//should return a list with the values in the specified columns from the user with the matching id
List<string> return_vals = base.GetValues(conn, vals, user_id);
//for some reason i am getting back the column names rather than the values in the fields
foreach(var v in return_vals)
{
Console.WriteLine(v);
}
}
}
What i have tried:
- Using getstring
- Using index rather than column names
- Specifying a specific column name
- Using while (reader.Read)
- Requesting different number of columns
I have used this method during the login section and it works perfectly there (code below). I can't figure out why it doesnt work here (code above) aswell.
static Boolean Login(MySqlConnection conn)
{
Console.Write("Username: ");
string username = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
string query = "SELECT user_id, username, password FROM Users WHERE username=#username";
Dictionary<string, string> vars = new Dictionary<string, string>
{
["#username"] = username
};
MySqlDataReader reader = SQLControler.SqlQuery(conn, query, vars, 0);
Boolean valid_login = ValidLogin(reader, password);
return (valid_login);
}
static Boolean ValidLogin(MySqlDataReader reader, string password)
{
Boolean return_val;
if (reader.Read())
{
//currently just returns the password as is, I will implement the hashing later
password = PasswordHash(password);
if (password == reader["password"].ToString())
{
MainProgram.user_id = Convert.ToInt32(reader["user_id"]);
return_val = true;
}
else
{
return_val = false;
}
}
else
{
return_val = false;
}
reader.Close();
return return_val;
}
The problem is here:
string args = "";
for (int i = 0; i < vals.Count(); i++)
{
args = args + "#" + vals[i];
vars.Add("#" + vals[i], vals[i]);
// ...
}
string query = "SELECT " + args + " FROM Users WHERE user_id = #user_id";
This builds a query that looks like:
SELECT #user_forename, #user_surname, #user_role, #user_status FROM Users WHERE user_id = #user_id;
Meanwhile, vars.Add("#" + vals[i], vals[i]); ends up mapping #user_forename to "user_forename" in the MySqlParameterCollection for the query. Your query ends up selecting the (constant) value of those parameters for each row in the database.
The solution is:
Don't prepend # to the column names you're selecting.
Don't add the column names as variables to the query.
You can do this by replacing that whole loop with:
string args = string.Join(", ", vals);
I am trying to build some basic email functionality within a c# asp.net application. My skills are limited and I am learning.
I am trying to send a list of email addresses to the application. I get the following error when creating the list:
cannot convert from 'string' to 'SendGrid.Helpers.Mail.EmailAddress'
I can see that the list reader is bringing the email address column as a string and I need to convert this to the [SendGrid.Helpers.Mail.EmailAddress] but I have no idea how to do this.
protected async void sendButton_Click(object sender, EventArgs e)
{
// Prepare the email message info model
var apiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["SendGrid_API_Key"];
var client = new SendGridClient(apiKey);
var com = new SqlConnection("Myconn");
com.Open();
string qry = "SELECT EmailAddress FROM MyTable";
var con = new SqlCommand(qry, com);
//var recipients = new List<EmailAddress>{
//new EmailAddress("Recipient1#test.co.uk", "User 1"),
//new EmailAddress("Recipient2#test.co.uk", "User 2") };
List<EmailAddress> columnData = new List<EmailAddress>();
using (SqlCommand command = new SqlCommand(qry, com))
{
using (SqlDataReader bb = command.ExecuteReader())
{
while (bb.Read())
{
columnData.Add(bb.GetString(0));
}
}
}
var msg = new SendGridMessage();
msg.SetFrom(new EmailAddress("Sender#azure.com", "Me"));
var recipients3 = columnData;
msg.AddTos(recipients3);
msg.SetSubject("Without ttttt");
msg.AddContent(MimeType.Text, "Dear Sir or Madam,!");
msg.AddContent(MimeType.Html, "<p>Dear Sir or Madam,!</p>");
var response = await client.SendEmailAsync(msg);
}
}
As pointed out in the comments, you are trying to add a String into a list of email addresses:
while (bb.Read())
{
columnData.Add(bb.GetString(0)); //error is here.
}
What you need to to is create a new object EmailAddress - with your retrieve string as parameter for the EmailAddress constructor:
while (bb.Read())
{
columnData.Add(new EmailAddress(bb.GetString(0)));
}
Edit:
If you have another field in myTable then change your query to:
string qry = "SELECT EmailAddress, Car FROM MyTable";
Create a list to hold the car values:
I have assumed the Car column is a string
var columnDataCar = new List<string>();
Retrive the values:
while (bb.Read())
{
columnData.Add(new EmailAddress(bb.GetString(0)));
columnDataCar.Add(bb.GetString(1);
}
Now columnDataCar holds the data for the Car field.
foreach(var item in columnDataCar)
{
msg.AddContent(MimeType.Text, item);
}
Hope it helps.
I am using active directory for getting all the departsment and filtering distinct departments using linq query, below is my code
private static DomainController GetDomainController(string domainpath)
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath);
var domain = Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
return controller;
}
private static MyMethod()
{
var domainController = GetDomainController(ActiveDirectorySettings.DomainPath);
// Lookup the information in AD
var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind };
DirectorySearcher ds;
ds = new DirectorySearcher(ldapEntry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))"
};
ds.PropertiesToLoad.Add("department");
if (ds.FindAll().Count >= 1)
{
//DataSet du = DataReader.CheckAdUserExist();
var results = ds.FindAll();
var uniqueSearchResults = results.Cast<SearchResult>().Select(x => GetProperty(x,"department")).Distinct();
addUsersList.AddRange(uniqueSearchResults.Select(departmentName => new UsersAndDepartments
{
UserDepartment = departmentName
}));
}
}
I want to check the linq query result with the database whether department already exist or not, I am not sure how to do that?
If what you want is to create a simple database connection using SqlConnection you just need to query your DB using the department parameter you received from your AD request.
try{
SqlConnection connection = new SqlConnection("YourConnectionstring");
connection.Open();
//Your connection string can be found through your Server DB
//Now you go through your SearchResultCollection populated by SearchResult objects
foreach(SearchResult res in uniqueSearchResult){
SqlCommand cmd = new SqlCommand("Select * from yourTable where department=" +res.Properties["department"][0].ToString() + "", connection);
SqlDataReader reader = cmd.ExecuteReader();
//Here you verify if there are corresponding rows in your table
//with the request you have executed
if(!reader.HasRows()){
//If you have not found corresponding rows, then you add the department to your
//list
addUsersList.Add(res.Properties["department"][0].ToString());
}
}
connection.close();
}catch(Exception e){
Console.WriteLine("Exception caught : \n\n" + e.ToString();
}
This should work.
There are plenty of tutorials for this, but if you are making alot of requests I do not recommend using this connection method you will just lose too much time / organization, maybe try using a persistence Framework like Entity Framework :
https://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Hope this answers your question!
Here is my solution, I have solved it myself
private static DomainController GetDomainController(string domainpath)
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath);
var domain = Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
return controller;
}
private static MyMethod()
{
var domainController = GetDomainController(ActiveDirectorySettings.DomainPath);
// Lookup the information in AD
var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind };
DirectorySearcher ds;
ds = new DirectorySearcher(ldapEntry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))"
};
ds.PropertiesToLoad.Add("department");
if (ds.FindAll().Count >= 1)
{
// getting list of all departments from the database
var departmentsList = AllDepartments();
// getting list of all departments from active directory
var results = ds.FindAll();
// filtering distinct departments from the result
var uniqueSearchResults = results.Cast<SearchResult>().Select(x => GetProperty(x,"department")).Distinct();
// here firstly i am getting the department list from the database and checking it for null, then using linq query i am comparing the result with ad department results
if (departmentsList != null)
{
addUsersList.AddRange(from sResultSet in uniqueSearchResults
where !departmentsList.Exists(u => u.UserDepartment == sResultSet)
select new UsersAndDepartments
{
UserDepartment = sResultSet
});
}
else
{
addUsersList.AddRange(uniqueSearchResults.Select(departmentName => new UsersAndDepartments
{
UserDepartment = departmentName
}));
}
}
}