add dummy column in LINQ fetch query - asp.net

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();

Related

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.

Is it possible to check if an SQLite table exists.

I have the following code:
dbcon = DependencyService.Get<ISQLite>().GetConnection();
// create the tables
dbcon.CreateTable<Category>();
dbcon.CreateTable<Settings>();
var settings = dbcon.Table<Settings>().ToList();
if (settings.Count <= 0)
{
var noa = new Settings { Setting = "NumberOfAnswers", Value = 5 };
var cfs = new Settings { Setting = "CardFrontSide", Value = 0 };
dbcon.Insert(noa);
dbcon.Insert(cfs);
}
var categories = dbcon.Table<Category>().ToList();
if (categories.Count <= 0)
{
InsertCategory();
}
From what I can see the application is using SQLite-net
What I would like to know is if there is a way I can check to see if a table exists rather than do this which is to try and create it anyway and then try to check if it has rows in it.
This query will return the list of tables in the database
SELECT * FROM sqlite_master WHERE type = 'table';
You can filter it down to a single row for an "exists" check.
SELECT * FROM sqlite_master WHERE type = 'table' AND tbl_name = 'xyz';
You can do something like this:
public static bool TableExists<T> (SQLiteConnection connection)
{
const string cmdText = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
var cmd = connection.CreateCommand (cmdText, typeof(T).Name);
return cmd.ExecuteScalar<string> () != null;
}
Source
You can use the below codes
public bool IsTableExists(string tableName)
{
try
{
var tableInfo = database.GetConnection().GetTableInfo(tableName);
if(tableInfo.Count > 0)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
public SQLiteAsyncConnection database;
public ClientDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
}

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.

Return distinct items in asp-mvc4 list

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;

How to create auto generate id for ListOf rows returned

I am accessing list of data as shown below.
var result = (from Pages in PagesList.Items.OfType<SPListItem>()
select new ListImages
{
desc = Convert.ToString(Pages["Description"])
}).ToList();
What I want is to auto generate customized increamental id for the no of rows generated.
ex, slide-img-1, slide-img-2 etc.
public class ListImages
{
string _desc;
string _id;
public string id
{
get
{
if (_id != null)
return _id;
else
return string.Empty;
}
set { _id = value; }
}
public string desc
{
get
{
if (_desc != null)
return _desc;
else
return string.Empty;
}
set { _desc = value; }
}
}
Thanks,
Ashish
I don't know if it can be achieved with the Linq specific syntax, but writing your query like this, you could use the .Select() method that provides an index:
var result = PagesList.Items.OfType<SPListItem>()
.Select((page, index) => new ListImages
{
desc = Convert.ToString(page["Description"]),
id = String.Concat("slide-img-", index + 1)
})
.ToList();

Resources