Return distinct items in asp-mvc4 list - asp.net

How would I return a unique list 'listColl' I tried using 'Distinct9' at the bottom with 'return listColl;' but received an error.but it didnt work. Currently this return a duplicate list of items which populates a treeview coded in query.
public List<SPList> GetAllLibraries(string webURL)
{
var listColl = new List<SPList>();
ClientContext _ctx = new ClientContext(webURL);
try
{
var currentWeb = _ctx.Web;
var AllLists = currentWeb.Lists;
_ctx.Load(AllLists);
_ctx.ExecuteQuery();
var query = from list in currentWeb.Lists
where list.BaseType == BaseType.DocumentLibrary
select list;
var listCollection = _ctx.LoadQuery(query.Include(myList => myList.Title,
myList => myList.Id,
myList => myList.RootFolder.ServerRelativeUrl,
myList => myList.ParentWebUrl,
myList => myList.Hidden,
myList => myList.IsApplicationList));
_ctx.ExecuteQuery();
// /*
listColl.AddRange(from list in listCollection
where !list.Hidden
select new SPList
{
Title = list.Title,
ListGUID = list.Id.ToString(),
RootFolderServerRelativeUrl = list.RootFolder.ServerRelativeUrl,
ParentWebUrl = list.ParentWebUrl
});
// } */
foreach (var Item in listCollection)
{
listColl.Add(new SPList
{
Title = Item.Title,
RootFolderServerRelativeUrl = Item.RootFolder.ServerRelativeUrl,
ListGUID = Item.Id.ToString()
});
}
}
catch (Exception ex)
{
// error log
string error = ex.Message + " Error within GetAllLibraries ";
}
return listColl;
}

Can you do this?
return listColl.Distinct();

listColl.AddRange((from list in listCollection
where !list.Hidden
select new SPList
{
Title = list.Title,
ListGUID = list.Id.ToString(),
RootFolderServerRelativeUrl = list.RootFolder.ServerRelativeUrl,
ParentWebUrl = list.ParentWebUrl
}).Distinct());

A quick fix solved the problem in the mean time. The reason I can no do Distinct() is because of SPList.
List<SPList> distinct = new List<SPList>();
List<String> ids = new List<string>();
foreach (var lst in listColl)
{
if (!ids.Contains(lst.ListGUID))
{
distinct.Add(lst);
ids.Add(lst.ListGUID);
}
}
return distinct;

Related

Add data only once

I am updating data and then I am adding them back to my list. However if I pres the update button few times on the row I will get the same line repeated few times. Can you please help how to add updated data without duplication?
First I remove
private void OnItemSelected(DocumentData selectedItem)
{
var index = Results.IndexOf(selectedItem);
Results.Remove(selectedItem);
Navigation.PushPopupAsync(new EditPopUp(selectedItem, this, index));
}
And then I update
public void UpdateValue(DocumentData selectedItem, int index)
{
var detail = new DocumentData()
{
FieldValue = selectedItem.FieldValue,
FieldDescriptor = selectedItem.FieldDescriptor,
Size = LoadSize(),
Padding = LoadPadding(),
};
Results.Insert(index, detail);
}
check for the existence of a matching item before you insert
var exists = Results.Any(r => r.FieldValue == selectedItem.FieldValue && r.FieldDescriptor == selectedItem.FieldDescriptor);
if (!exists) {
var detail = new DocumentData()
{
FieldValue = selectedItem.FieldValue,
FieldDescriptor = selectedItem.FieldDescriptor,
Size = LoadSize(),
Padding = LoadPadding(),
};
Results.Insert(index, detail);
}

Use stored procedure for search method

I started with ASP.Net Core 2.0, I'm trying to rewrite a method GetAll by search use stored procedure. Here is method search:
public async Task<List<DepartmentTypeDto>> SearchDepartmentType()
{
EnsureConnectionOpen();
using (var command = CreateCommand("CM_DEPT_GROUP_Search", CommandType.StoredProcedure))
{
using (var dataReader = await command.ExecuteReaderAsync())
{
List<DepartmentTypeDto> result = new List<DepartmentTypeDto>();
while (dataReader.Read())
{
DepartmentTypeDto departmentTypeDto = new DepartmentTypeDto
{
GROUP_ID = dataReader["GROUP_ID"].ToString(),
GROUP_CODE = dataReader["GROUP_CODE"].ToString(),
GROUP_NAME = dataReader["GROUP_NAME"].ToString(),
NOTES = dataReader["NOTES"].ToString(),
RECORD_STATUS = dataReader["RECORD_STATUS"].ToString(),
MAKER_ID = dataReader["MAKER_ID"].ToString(),
CREATE_DT = Convert.ToDateTime(dataReader["CREATE_DT"]),
AUTH_STATUS = dataReader["AUTH_STATUS"].ToString(),
CHECKER_ID = dataReader["CHECKER_ID"].ToString(),
APPROVE_DT = Convert.ToDateTime(dataReader["APPROVE_DT"]),
AUTH_STATUS_NAME = dataReader["AUTH_STATUS_NAME"].ToString(),
RECORD_STATUS_NAME = dataReader["RECORD_STATUS_NAME"].ToString()
};
}
return result;
}
}
}
Here is the service:
public async Task<PagedResultDto<GetDepartmentTypeForView>> GetAll(GetAllDepartmentTypesInput input)
{
var filteredDepartmentTypes = _departmentTypeRepository.SearchDepartmentType();
var query = (from o in filteredDepartmentTypes
select new GetDepartmentTypeForView() { DepartmentType = ObjectMapper.Map<DepartmentTypeDto>(o) });
var totalCount = await query.CountAsync();
var departmentTypes = await query
.OrderBy(input.Sorting ?? "departmentType.id asc")
.PageBy(input)
.ToListAsync();
return new PagedResultDto<GetDepartmentTypeForView>(totalCount, departmentTypes);
}
But I get an error:
Task<List<DepartmentTypeDto>> does not contain a definition for Select
Does anyone know what I should do? I work on Asp.Net Zero.
I changed my search method
public IQueryable<DepartmentTypeView> SearchDepartmentType(GetAllDepartmentTypesInput input, int top)
{
try
{
var GROUP_FILTER = input.Filter;
var GROUP_CODE = input.GROUP_CODEFilter;
var GROUP_NAME = input.GROUP_NAMEFilter;
var AUTH_STATUS = input.AUTH_STATUSFilter;
var result = Context.Query<DepartmentTypeView>().FromSql($"EXEC CM_DEPT_GROUP_Search #p_GROUP_FILTER = {GROUP_FILTER}, #p_GROUP_CODE={GROUP_CODE}, #p_GROUP_NAME={GROUP_NAME}, #p_AUTH_STATUS={AUTH_STATUS}, #p_TOP={top}");
return result;
}
catch
{
return null;
}
}
and in the service, I call that function
var filteredDepartmentTypes = _departmentTypeRepository.SearchDepartmentType(input,100);
I also create new class to keep the result and don't forget to map that class with DTO class
configuration.CreateMap<DepartmentTypeView, DepartmentTypeDto>();
It works for me.

Retrieve an Entity value to add to return parameter

I have this method:
private List < ReportParameter > ParametrosReporte() {
List < ReportParameter > Parametros = new List < ReportParameter > ();
try {
int ? int_Ejercicio = this.radcmbEjercicio.SelectedItem == null ? 0 : this.radcmbEjercicio.SelectedValue.ToInt();
int ? int_Periodo = this.radcmbPeriodo.SelectedItem == null ? 0 : this.radcmbPeriodo.SelectedValue.ToInt();
int ? int_BSC = this.radcmbBSC.SelectedItem == null ? 0 : this.radcmbBSC.SelectedValue.ToInt();
Parametros.Add(Reportes.ParametrosReporte("pe_Ejercicio", int_Ejercicio.ToString()));
Parametros.Add(Reportes.ParametrosReporte("pe_Mes", int_Periodo.ToString()));
Parametros.Add(Reportes.ParametrosReporte("pe_BSC", int_BSC.ToString()));
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = ((Usuario) Session["User"]).UsuarioID,
}
};
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", UsuarioID ));
return Parametros;
} catch (Exception ex) {
throw new System.ArgumentException("Error en ParametrosReporte", ex);
}
}
As you can see I have logic to retrieve user who is logged in as:
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = ((Usuario) Session["User"]).UsuarioID,
}
};
but before retrieve it, I want to call it into Parametros.Add like:
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", UsuarioID ));
But I canĀ“t because UsuarioID is out of scope and it throws me
UsuarioID does not exist in the current context
How can I call it and attach to my Parametros.Add?
You can just create a local variable above your creation of catBSC and then use that in both locations:
var usuarioID = ((Usuario) Session["User"]).UsuarioID
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = usuarioID
}
};
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", usuarioID));
You can replace var with the actual type, but I didn't want to make an assumption about what this was in your scenario.

List not populating dropdown

I am using a standard list method for my lookups I use this for winforms and works fine just trying to re use on web and its not displaying my items.
public List<SISLookupLists> GetGender()
{
List<SISLookupLists> lookups = new List<SISLookupLists>();
try
{
var q = from lookup in schoolEntities.Genders
orderby lookup.description
select new
{
Code = lookup.code,
Description = lookup.description.Trim()
};
if (q != null)
{
Array.ForEach(q.ToArray(), l =>
{
lookups.Add(new SISLookupLists(l.Code, l.Description));
});
}
}
catch (Exception ex)
{
throw new EntityContextException("GetGender failed.", ex);
}
return lookups;
}
public SISDBContext _db = new SISDBContext();
rdGender.DataSource = _db.GetGender();
rdGender.DataTextField = "Description";
rdGender.DataValueField= "Code";
rdGender.DataBind();
Any idea what I am doing wrong here guys.

add dummy column in LINQ fetch query

How to return the List in LINQ query while adding a dummy column,
How to return qry as LIST.
public static List<MSDNMagazine.emp> FetchEmp()
{
try
{
MSDNMagazine.JsonDataContext context = new MSDNMagazine.JsonDataContext();
var qry = from p in context.emps
select new
{
emp_cod = p.emp_cod,
emp_nam = p.emp_nam,
test = "0"
};
return (List< >)qry;
}
catch (Exception ex)
{
throw ex;
}
}
select new emp //the name of the class
{
emp_cod = p.emp_cod,
emp_nam = p.emp_nam,
test = "0"
};
return qry.ToList();
Use the ToList() Extension method.
return qry.ToList();

Resources